精华内容
下载资源
问答
  • 包含了在MVVM模式下的数据绑定、命令和事件、PasswordBox的绑定、RadioButton等一对多控件的绑定、关闭窗口和打开新窗口和数据验证等内容。
  • WPF登录界面demo

    千次阅读 2019-07-08 08:23:53
    WPF登录界面demo用了自定义按钮样式和添加了窗体阴影,并加入了旋转、缩放等动画实现的,运行效果如下: App.xaml页面代码: <Application x:Class="WPF_Client.App" xmlns=...
    1. 概述:

    此WPF登录界面demo用了自定义按钮样式和添加了窗体阴影,并加入了旋转、缩放等动画实现的,运行效果如下:

    App.xaml页面代码:

    <Application x:Class="WPF_Client.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:local="clr-namespace:WPF_Client"
                 StartupUri="LoginWindow.xaml">
        <Application.Resources>
            <!--登录窗体阴影效果和旋转缩放动画。-->
            <Style x:Key="window_Shadow" TargetType="{x:Type Window}">
                <!--对象中心点用来定义所有RenderTransform变换中相对位置的的参考点,默认为图形的左上即(0,0),
                    该属性值为相对值,介于 0 和 1 之间的值被解释为每对 x,y 轴中的当前元素的范围的因素-->
                <!--<Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>-->
                <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type Window}">
                                <Grid Margin="10">
                                <!--x:Static 引用中定义的任何静态的值的代码实体公共语言规范 (CLS)– 合规的方式。 引用的静态属性可以用于提供在 XAML 中属性的值
                                  SystemColors 定义的所需的静态成员的类型的名称。
                                  WindowBrushKey 使用WindowBrushKey创建对用于绘制窗口的客户端区域背景的画笔的动态引用。 如果更改画笔,将自动更新此动态引用。 若要创建的静态引用,不会自动更新,请使用WindowBrush。-->
                                <Rectangle Name="rt" Fill="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
                                        <Rectangle.Effect>
                                        <!--DropShadowEffect是WPF中一个阴影效果的类
                                            BlurRadius模糊半径属性,获取或设置阴影边缘的定义(阴影有多模糊)
                                            ShadowDepth属性设置投影距纹理下方的距离-->
                                        <DropShadowEffect BlurRadius="12" ShadowDepth="0"/>
                                        </Rectangle.Effect>
                                    <Rectangle.RenderTransform>
                                        <TransformGroup>
                                            <!--ScaleTransform:能够让某对象产生缩放变化。-->
                                            <ScaleTransform CenterX="240" CenterY="140"/>
                                            <!--RotateTransform:能够让某对象产生旋转变化,根据中心点进行顺时针旋转或逆时针旋转。-->
                                            <RotateTransform CenterX="240" CenterY="140"/>
                                        </TransformGroup>
                                    </Rectangle.RenderTransform>
                                    </Rectangle>
                                <!--SnapsToDevicePixels获取或设置一个值,该值确定在呈现过程中,此元素的呈现是否应使用特定于设备的像素设置。 这是依赖项属性。-->
                                <Border Background="{TemplateBinding Background}"
                                        BorderBrush="{TemplateBinding BorderBrush}"
                                        BorderThickness="{TemplateBinding BorderThickness}"
                                        Padding="{TemplateBinding Margin}"
                                        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                        CornerRadius="5">
                                        <ContentPresenter />
                                    </Border>
                                </Grid>
                            <!--定义触发器-->
                            <ControlTemplate.Triggers>
                                <!--属性触发器: 鼠标移入移出-->
                                <EventTrigger RoutedEvent="Window.Loaded">
                                    <BeginStoryboard>
                                        <Storyboard BeginTime="0:0:0">
                                            <!--控制窗体透明度-->
                                            <DoubleAnimation Storyboard.TargetProperty="(UIElement.Opacity)" To="1" Duration="0:0:2"/>
                                            <!--控制窗体放大和缩小-->
                                            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.Children[0].ScaleX" From="0" To="1" Duration="0:0:2" Storyboard.TargetName="rt"/>
                                            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.Children[0].ScaleY" From="0" To="1" Duration="0:0:2" Storyboard.TargetName="rt"/>
                                            <!--设置RotateTransform(旋转变化):属性Angle(旋转角度)从0到0历时360秒-->
                                            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.Children[1].Angle" From="0" To="360" Duration="0:0:2" SpeedRatio="2" Storyboard.TargetName="rt"/>
                                        </Storyboard>
                                    </BeginStoryboard>
                                </EventTrigger>
                            </ControlTemplate.Triggers>
                            <!--定义触发器_End-->
                        </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            <!--自定义button控件-->
            <Style x:Key="NewButton" TargetType="{x:Type Button}">
                <Setter Property="Padding" Value="1"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Grid Cursor="Hand">
                                <Border x:Name="_Border" Background="{TemplateBinding Background}" CornerRadius="5" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                                </Border>
                                <!--ContentPresenter的作用就是显示内容,但Control类没有这个Content属性,所以在Control类之上写了一个ContentControl类,然后ContentPresenter(其显示依赖于ContentControl类)负责将ContentControl的Content属性显示出来。每个控件都有一个默认的ContentPresenter用于显示Content内容,这种控件为内容控件-->
                                <!--SnapsToDevicePixels获取或设置一个值,该值确定在呈现过程中,此元素的呈现是否应使用特定于设备的像素设置。 这是依赖项属性。-->
                                <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                            </Grid>
                            <!--定义触发器-->
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Background" TargetName="_Border">
                                        <Setter.Value>
                                            <SolidColorBrush Color="#ef3c62"/>
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>
                                <Trigger Property="IsEnabled" Value="False">
                                    <Setter Property="Background" TargetName="_Border">
                                        <Setter.Value>
                                            <SolidColorBrush Color="Gray"/>
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>
                            </ControlTemplate.Triggers>
                            <!--定义触发器_End-->
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Application.Resources>
    </Application>

    XAML代码:

    <Window x:Class="WPF_Client.LoginWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            WindowStyle="None"
            ResizeMode="NoResize" 
            Background="Transparent" 
            AllowsTransparency="True"
            WindowStartupLocation="CenterScreen"
            Title="LoginWindow" Height="300" Width="500" Loaded="Window_Loaded"
            Style="{StaticResource window_Shadow}"
            >
        <!--窗口资源-->
        <Window.Resources>
            <!--故事版-->
            <Storyboard x:Key="Storyboard1" BeginTime="0:0:0">
                <!--控制窗体透明度-->
                <DoubleAnimation Storyboard.TargetProperty="(UIElement.Opacity)" From="0" To="1" Duration="0:0:2" Storyboard.TargetName="dp"/>
                <!--控制窗体放大和缩小-->
                <DoubleAnimation Storyboard.TargetProperty="RenderTransform.Children[0].ScaleX" From="0" To="1" Duration="0:0:2" Storyboard.TargetName="dp"/>
                <DoubleAnimation Storyboard.TargetProperty="RenderTransform.Children[0].ScaleY" From="0" To="1" Duration="0:0:2" Storyboard.TargetName="dp"/>
                <!--设置RotateTransform(旋转变化):属性Angle(旋转角度)从50到0历时2秒-->
                <DoubleAnimation Storyboard.TargetProperty="RenderTransform.Children[1].Angle" From="0" To="360" Duration="0:0:2" SpeedRatio="2" Storyboard.TargetName="dp"/>
            </Storyboard>
        </Window.Resources>
        <!--窗体触发器-->
        <Window.Triggers>
            <!--事件触发器-->
            <EventTrigger RoutedEvent="Window.Loaded">
                <!--窗体触发的时候调用故事版 Storyboard1-->
                <!--StaticResource  引用资源。-->
                <BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
            </EventTrigger>
        </Window.Triggers>
        <!--停靠面板:布局页面-->
        <DockPanel Name="dp">
            <!--设置停靠面板变形旋转-->
            <DockPanel.RenderTransform>
                <TransformGroup>
                    <!--能够让某对象产生缩放变化。包括属性ScaleX、ScaleY、CenterX、CenterY,其中ScaleX、ScaleY属性表示对象在X、Y轴进行缩放的倍数,使用CenterX 和 CenterY属性指定一个中心点。-->
                    <ScaleTransform CenterX="240" CenterY="140"/>
                    <!--RotateTransform:能够让某对象产生旋转变化,根据中心点进行顺时针旋转或逆时针旋转。-->
                    <RotateTransform CenterX="240" CenterY="140"/>
                </TransformGroup>
            </DockPanel.RenderTransform>
            <!--页面构成-->
            <Grid>
                <Image Source="Images/train2.jpg" Stretch="Fill"/>
                <Image Source="Images/icon.png" Width="180" Height="30" VerticalAlignment="Top" Margin="-290,20,-290,0"/>
                <Rectangle Fill="#fcfcfb" Opacity="0.3" Width="350" Height="180" RadiusX="5" RadiusY="5" Stroke="Gray" VerticalAlignment="Top" Margin="-290,65,-290,0"/>
                
                <TextBlock  Background="#eeeeee" Width="50" Height="30" VerticalAlignment="Top" Margin="-490,95,-290,0" Text="帐号" TextAlignment="Center" Padding="8"/>
                <!--MaxLength属性:输入值的最大长度,不包含硬编码中Text的字符长度-->
                <!--TextWrapping:如果设置成wrap ,就表示当文本长度超过容器长度时可以自动换行。
                                        默认为no wrap,即当文本长度超过容器长度时,文本超出部分被遮挡。-->
                <!--AcceptsReturn:允许回车换行操作-->
                <TextBox Background="White" Width="200" Height="30" AcceptsReturn="True" MaxLength="20"  
                                TextWrapping="NoWrap" FontSize="16" Margin="50,-60,0,0" Padding="4"/>
                <TextBlock  Background="#eeeeee" Width="50" Height="30" VerticalAlignment="Top" Margin="-490,135,-290,0" Text="密码" TextAlignment="Center" Padding="8"/>
                <PasswordBox Background="White" Width="200" Height="30" FontSize="16" Margin="50,20,0,0" MaxLength="20" Padding="4"></PasswordBox>
                <!--Content:作用与TextBox的Text属性一样,但其数据类型为object,即可放任何对象,但只能存放一个对象-->
                <Button Name="btn_Login" Style="{StaticResource NewButton}" 
                        Content="登录" 
                        Height="35"
                        Width="70"
                        FontSize="19"                    
                        Cursor="Hand"
                        Background="#fe0338"
                        Foreground="White"
                        HorizontalAlignment="Left"
                        VerticalAlignment="Top" 
                        Margin="130,180,0,0" 
                        FontFamily="Vivaldi">
                </Button>
                <!--Cursor:当光标进入控件范围时使用的鼠标指针-->
                <Button Style="{StaticResource NewButton}"                    
                        Name="btn_Cancel" 
                        Content="退出" 
                        Height="35" 
                        Width="70" 
                        FontSize="19"                   
                        Foreground="White"
                        Background="#fe0338" 
                        HorizontalAlignment="Left" 
                        VerticalAlignment="Top" 
                        Margin="280,180,-290,0"
                        Cursor="Hand"
                        FontFamily="Vivaldi"
                        Click="btn_btn_Cancel_Click"/>
            </Grid>
        </DockPanel>
    </Window>

     

    展开全文
  • WPF开发实例——仿QQ登录界面

    万次阅读 多人点赞 2015-10-14 21:00:21
    刚开始学WPF,自己写了个小东西,说实话写的并不好,好多东西不懂只是用现在懂的东西来写的,效果如图 下面是源码,理论上很简单,我直接放代码了。 自定义用户控件RightButton.xaml <UserControl x:Class="Wpf...

    刚开始学WPF,自己写了个小东西,说实话写的并不好,好多东西不懂只是用现在懂的东西来写的,效果如图

    下面是源码,理论上很简单,我直接放代码了。

    自定义用户控件RightButton.xaml

    <UserControl x:Class="WpfApplication8.RigthButton"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" 
                 d:DesignHeight="300" d:DesignWidth="300">
        <UserControl.Resources>
            <Style x:Key="CloseButton" TargetType="{x:Type Button}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Grid>
                                <Rectangle x:Name="rectangle">
                                    <Rectangle.Fill>
                                        <ImageBrush ImageSource="skin/close_normal.png"/>
                                    </Rectangle.Fill>
                                </Rectangle>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsFocused" Value="True"/>
                                <Trigger Property="IsDefaulted" Value="True"/>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Fill" TargetName="rectangle">
                                        <Setter.Value>
                                            <ImageBrush ImageSource="skin/close_hot.png"/>
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter Property="Fill" TargetName="rectangle">
                                        <Setter.Value>
                                            <ImageBrush ImageSource="skin/close_down.png"></ImageBrush>
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>
                                <Trigger Property="IsEnabled" Value="False"/>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
    
            <Style x:Key="SmallButton" TargetType="{x:Type Button}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Grid>
                                <Rectangle x:Name="rectangle">
                                    <Rectangle.Fill>
                                        <ImageBrush ImageSource="skin/small_normal.png"/>
                                    </Rectangle.Fill>
                                </Rectangle>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsFocused" Value="True"/>
                                <Trigger Property="IsDefaulted" Value="True"/>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Fill" TargetName="rectangle">
                                        <Setter.Value>
                                            <ImageBrush ImageSource="skin/small_hot.png"/>
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter Property="Fill" TargetName="rectangle">
                                        <Setter.Value>
                                            <ImageBrush ImageSource="skin/small_down.png"></ImageBrush>
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>
                                <Trigger Property="IsEnabled" Value="False"/>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
    
            <Style x:Key="DownButton" TargetType="{x:Type Button}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Grid>
                                <Rectangle x:Name="rectangle">
                                    <Rectangle.Fill>
                                        <ImageBrush ImageSource="skin/down_normal.png"/>
                                    </Rectangle.Fill>
                                </Rectangle>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsFocused" Value="True"/>
                                <Trigger Property="IsDefaulted" Value="True"/>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Fill" TargetName="rectangle">
                                        <Setter.Value>
                                            <ImageBrush ImageSource="skin/down_hot.png"/>
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>
                                <Trigger Property="IsPressed" Value="True">
                                    <Setter Property="Fill" TargetName="rectangle">
                                        <Setter.Value>
                                            <ImageBrush ImageSource="skin/down_down.png"></ImageBrush>
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>
                                <Trigger Property="IsEnabled" Value="False"/>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </UserControl.Resources>
        <StackPanel Orientation="Horizontal">
            <Button Click="Button_Click" Width="30" Height="30" Style="{StaticResource DownButton}"></Button>
            <Button Click="Button_Click_1" Width="30" Height="30" Style="{StaticResource SmallButton}"></Button>
            <Button Click="Button_Click_2" Width="30" Height="30" Style="{StaticResource CloseButton}"></Button>
        </StackPanel>
    </UserControl>
    
    RightButton.xmal.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace WpfApplication8
    {
        /// <summary>
        /// RigthButton.xaml 的交互逻辑
        /// </summary>
        public partial class RigthButton : UserControl
        {
            public RigthButton()
            {
                InitializeComponent();
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
    
            }
    
            private void Button_Click_1(object sender, RoutedEventArgs e)
            {
                
            }
    
            private void Button_Click_2(object sender, RoutedEventArgs e)
            {
                Application.Current.Shutdown();
            }
        }
    }
    
    MainWindow.xaml

    <Window x:Class="WpfApplication8.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:loc="clr-namespace:WpfApplication8"
            Title="企鹅球球" Height="330" Width="430" AllowsTransparency="True" WindowStyle="None" MouseDown="Window_MouseDown">
    	<Window.Resources>
    		<Style x:Key="FocusVisual">
    			<Setter Property="Control.Template">
    				<Setter.Value>
    					<ControlTemplate>
    						<Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
    					</ControlTemplate>
    				</Setter.Value>
    			</Setter>
    		</Style>
    		<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
    		<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
    		<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
    		<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
    		<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
    		<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
    		<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
    		<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
    		<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
    		<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
    			<Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
    			<Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
    			<Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
    			<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    			<Setter Property="BorderThickness" Value="1"/>
    			<Setter Property="HorizontalContentAlignment" Value="Center"/>
    			<Setter Property="VerticalContentAlignment" Value="Center"/>
    			<Setter Property="Padding" Value="1"/>
    			<Setter Property="Template">
    				<Setter.Value>
    					<ControlTemplate TargetType="{x:Type Button}">
    						<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
    							<ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    						</Border>
    						<ControlTemplate.Triggers>
    							<Trigger Property="IsDefaulted" Value="true">
    								<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
    							</Trigger>
    							<Trigger Property="IsMouseOver" Value="true">
    								<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
    								<Setter Property="Background" TargetName="border" Value="#FF51B3EC"/>
    							</Trigger>
    							<Trigger Property="IsPressed" Value="true">
    								<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
    								<Setter Property="Background" Value="#FF3FA4E8"/>
    								<Setter Property="Background" TargetName="border" Value="#FF42B5F0"/>
    							</Trigger>
    							<Trigger Property="IsEnabled" Value="false">
    								<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
    								<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
    								<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
    							</Trigger>
    						</ControlTemplate.Triggers>
    					</ControlTemplate>
    				</Setter.Value>
    			</Setter>
    		</Style>
    		<SolidColorBrush x:Key="OptionMark.Static.Background" Color="#FFFFFFFF"/>
    		<SolidColorBrush x:Key="OptionMark.Static.Border" Color="#FF707070"/>
    		<Style x:Key="OptionMarkFocusVisual">
    			<Setter Property="Control.Template">
    				<Setter.Value>
    					<ControlTemplate>
    						<Rectangle Margin="14,0,0,0" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
    					</ControlTemplate>
    				</Setter.Value>
    			</Setter>
    		</Style>
    		<SolidColorBrush x:Key="OptionMark.MouseOver.Background" Color="#FFF3F9FF"/>
    		<SolidColorBrush x:Key="OptionMark.MouseOver.Border" Color="#FF5593FF"/>
    		<SolidColorBrush x:Key="OptionMark.MouseOver.Glyph" Color="#FF212121"/>
    		<SolidColorBrush x:Key="OptionMark.Disabled.Background" Color="#FFE6E6E6"/>
    		<SolidColorBrush x:Key="OptionMark.Disabled.Border" Color="#FFBCBCBC"/>
    		<SolidColorBrush x:Key="OptionMark.Disabled.Glyph" Color="#FF707070"/>
    		<SolidColorBrush x:Key="OptionMark.Pressed.Background" Color="#FFD9ECFF"/>
    		<SolidColorBrush x:Key="OptionMark.Pressed.Border" Color="#FF3C77DD"/>
    		<SolidColorBrush x:Key="OptionMark.Pressed.Glyph" Color="#FF212121"/>
    		<SolidColorBrush x:Key="OptionMark.Static.Glyph" Color="#FF212121"/>
    		<Style x:Key="CheckBoxStyle1" TargetType="{x:Type CheckBox}">
    			<Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
    			<Setter Property="Background" Value="{StaticResource OptionMark.Static.Background}"/>
    			<Setter Property="BorderBrush" Value="{StaticResource OptionMark.Static.Border}"/>
    			<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    			<Setter Property="BorderThickness" Value="1"/>
    			<Setter Property="Template">
    				<Setter.Value>
    					<ControlTemplate TargetType="{x:Type CheckBox}">
    						<Grid x:Name="templateRoot" Background="Transparent" SnapsToDevicePixels="True">
    							<Grid.ColumnDefinitions>
    								<ColumnDefinition Width="Auto"/>
    								<ColumnDefinition Width="*"/>
    							</Grid.ColumnDefinitions>
    							<Border x:Name="checkBoxBorder" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
    								<Grid x:Name="markGrid">
    									<Path x:Name="optionMark" Data="F1 M 9.97498,1.22334L 4.6983,9.09834L 4.52164,9.09834L 0,5.19331L 1.27664,3.52165L 4.255,6.08833L 8.33331,1.52588e-005L 9.97498,1.22334 Z " Fill="{StaticResource OptionMark.Static.Glyph}" Margin="1" Opacity="0" Stretch="None"/>
    									<Rectangle x:Name="indeterminateMark" Fill="{StaticResource OptionMark.Static.Glyph}" Margin="2" Opacity="0"/>
    								</Grid>
    							</Border>
    							<ContentPresenter x:Name="contentPresenter" Grid.Column="1" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    						</Grid>
    						<ControlTemplate.Triggers>
    							<Trigger Property="HasContent" Value="true">
    								<Setter Property="FocusVisualStyle" Value="{StaticResource OptionMarkFocusVisual}"/>
    								<Setter Property="Padding" Value="4,-1,0,0"/>
    							</Trigger>
    							<Trigger Property="IsMouseOver" Value="true">
    								<Setter Property="Background" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.MouseOver.Background}"/>
    								<Setter Property="BorderBrush" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.MouseOver.Border}"/>
    								<Setter Property="Fill" TargetName="optionMark" Value="{StaticResource OptionMark.MouseOver.Glyph}"/>
    								<Setter Property="Fill" TargetName="indeterminateMark" Value="{StaticResource OptionMark.MouseOver.Glyph}"/>
    							</Trigger>
    							<Trigger Property="IsEnabled" Value="false">
    								<Setter Property="Background" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.Disabled.Background}"/>
    								<Setter Property="BorderBrush" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.Disabled.Border}"/>
    								<Setter Property="Fill" TargetName="optionMark" Value="{StaticResource OptionMark.Disabled.Glyph}"/>
    								<Setter Property="Fill" TargetName="indeterminateMark" Value="{StaticResource OptionMark.Disabled.Glyph}"/>
    							</Trigger>
    							<Trigger Property="IsPressed" Value="true">
    								<Setter Property="Background" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.Pressed.Background}"/>
    								<Setter Property="BorderBrush" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.Pressed.Border}"/>
    								<Setter Property="Fill" TargetName="optionMark" Value="{StaticResource OptionMark.Pressed.Glyph}"/>
    								<Setter Property="Fill" TargetName="indeterminateMark" Value="{StaticResource OptionMark.Pressed.Glyph}"/>
    							</Trigger>
    							<Trigger Property="IsChecked" Value="true">
    								<Setter Property="Opacity" TargetName="optionMark" Value="1"/>
    								<Setter Property="Opacity" TargetName="indeterminateMark" Value="0"/>
    								<Setter Property="Background" TargetName="markGrid" Value="blue"/>
    								<Setter Property="Fill" TargetName="optionMark" Value="white"/>
    							</Trigger>
    							<Trigger Property="IsChecked" Value="{x:Null}">
    								<Setter Property="Opacity" TargetName="optionMark" Value="0"/>
    								<Setter Property="Opacity" TargetName="indeterminateMark" Value="1"/>
    							</Trigger>
    						</ControlTemplate.Triggers>
    					</ControlTemplate>
    				</Setter.Value>
    			</Setter>
    		</Style>
    	</Window.Resources>
        <StackPanel>
            <Grid Height="180">
            	<Grid.Background>
            		<ImageBrush ImageSource="bckpic.jpg"/>
            	</Grid.Background>
                <StackPanel Width="150" Height="30" HorizontalAlignment="Right" VerticalAlignment="Top">
                    <loc:RigthButton HorizontalAlignment="Right"></loc:RigthButton>
                </StackPanel>
            </Grid>
            <StackPanel Height="150">
                <StackPanel Orientation="Horizontal" >
                    <Border Height="80" Width="80" Margin="35,10,10,10" CornerRadius="5" BorderBrush="Gray" BorderThickness="1">
                        <Border.Background>
                            <ImageBrush ImageSource="touxiang1.jpg"/>
                        </Border.Background>
                    </Border>
                    <StackPanel Width="180" Height="89" Margin="10,10,0,0">
                        <Border BorderBrush="Gray" CornerRadius="5" BorderThickness="1">
                            <StackPanel Width="180" Height="60">
                                <TextBox Height="25" Width="180" Background="{x:Null}" BorderThickness="0,0,0,1" Margin="0,5,0,0" FontSize="14" Foreground="Gray">用户名</TextBox>
                                <TextBox Height="25" Width="180" Background="{x:Null}" BorderThickness="0" Margin="0,2,0,0" FontSize="14" Foreground="Gray">密码</TextBox>
                            </StackPanel>
                        </Border>
                       
                        <StackPanel Orientation="Horizontal" Height="15" Width="180" Margin="0,10,0,0">
                            <CheckBox Style="{DynamicResource CheckBoxStyle1}">记住密码</CheckBox>
                            <CheckBox Style="{DynamicResource CheckBoxStyle1}" Margin="42,0,0,0">自动登陆</CheckBox>
                        </StackPanel>
    
                    </StackPanel>
    
                    <StackPanel Height="60" Margin="15">
                        <TextBlock Height="30">
    						<Hyperlink NavigateUri="http://zc.qq.com">注册账号</Hyperlink>
    					</TextBlock>
                        <TextBlock Height="30">
    						<Hyperlink NavigateUri="http://aq.qq.com/">找回密码</Hyperlink>
    					</TextBlock>
                    </StackPanel>
    
                </StackPanel>
    
                <Border Height="30" Width="180" Margin="20,5,0,0" CornerRadius="5" BorderBrush="#FF0E95F1" BorderThickness="1">
                    <Button Height="30" FontWeight="Bold" Width="180" Content="登  陆" FontFamily="宋体" Foreground="White" Background="#FF0E95F1" BorderThickness="0" Style="{DynamicResource ButtonStyle1}"></Button>
                </Border>    
            </StackPanel>
        </StackPanel>
    </Window>
    


    展开全文
  • WPF实例实例比较多)

    热门讨论 2017-11-08 10:06:37
    WPF实例实例比较多) (wpf窗体继承)RibbonStyle2.zip (赛车游戏)GrandPrix_SRC.zip CustomRulesMVVM.zip ...WPF界面下的会员登录.rar 基于插件式的开发框架源码.rar 漂亮的WPF界面框架(OSGi.NET插件)源码.rar
  • WPF 登录菜单页面跳转

    2019-10-12 17:28:56
    根据背景图片等比放置控件,然后通过消息订阅和发布的...登录界面的输入框显示水印的提示信息,输入值后水印提示消息消失,并且在登录页面的ViewModel中绑定界面中输入的密码的值,每个不同的菜单对应不同的页面跳转
  • WPF大量的实例.rar

    2019-06-17 09:07:07
    treeview.zip WPF.MDI.rar WpfApplication1.zip WPF中UserControl如何访问它所属的Window的控件或事件.txt WPF之DataGrid.rar WPF动态添加行列DATAGRID.rar WPF界面下的会员登录.rar 基于插件式的开发框架源码.rar ...
  • WPF多线程实例

    2019-05-08 15:46:56
    一个WPF多线程实例:两个列表listbox,每秒从第一个列表中随机抽取出一项,然后添加到第二个列表中,同时界面实现实时更新
  • WPF实例系列一:登录、注册界面设计 文章目录WPF实例系列一:登录、注册界面设计前言一、实例演示1. 登录界面展示2. 注册界面展示3. 数据存储4. 效果演示二、结构及源码1.主界面跳转登录界面设计2.登录界面设计3....

    WPF实例系列一:登录、注册界面设计



    前言

    本实例将展示利用WPF设计登录界面、注册界面,并实现相应的功能,其中账户数据将存储在excel表中(补充:增加Mysql数据库存储账户数据)。


    一、实例演示

    1. 登录界面展示

    ​​​在这里插入图片描述

    2. 注册界面展示

    在这里插入图片描述

    3. 数据存储

    在这里插入图片描述

    4. 效果演示

    在这里插入图片描述

    二、结构及源码

    1.主界面跳转登录界面设计

    MainWindow.xaml.cs跳转登录界面代码如下:

    using System;
    using System.Windows;
    using System.Windows.Threading;
    
    namespace sample5
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            //public int play_state = 1;  
            public MainWindow()
            {
                InitializeComponent();
    
                #region 登录界面加载及验证
                //显示登陆界面,验证后返回。
                LoginWindow loginWindow = new LoginWindow();
                loginWindow.ShowDialog();
                if (loginWindow.DialogResult != Convert.ToBoolean(1))
                {
                    this.Close();
                }
                //显示登陆界面 结束
                #endregion 
             }
         }
     }     
    

    2.登录界面设计

    Xaml代码如下(添加1个Nuget库:MaterialDesignThemes.3.1.0-ci981 ;可参考):

    <Window x:Class="sample5.LoginWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:sample5"
            mc:Ignorable="d"
            Title="用户登录" Height="500" Width="350" 
            ResizeMode="NoResize" 
            WindowStartupLocation="CenterScreen" 
            WindowStyle="None" 
            MouseLeftButtonDown="MoveWindow_MouseLeftButtonDown"
            FontFamily="Segoe UI Emoji">
    
        <Grid>
            <Rectangle Height="280" VerticalAlignment="Top">
                <Rectangle.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="#FF2281D1"/>
                        <GradientStop Color="#FF34268A" Offset="1"/>
                        <GradientStop Color="#FF33288B" Offset="0.546"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
            <Rectangle Height=" 220" VerticalAlignment="Bottom" >
                <Rectangle.Fill>
                    <SolidColorBrush Color="Snow" />
                </Rectangle.Fill>
            </Rectangle>
    
            <Rectangle Width="280" Height="240" VerticalAlignment="Bottom" Margin="0,80" RadiusY="10" RadiusX="10" Fill="White">
                <Rectangle.Effect>
                    <DropShadowEffect BlurRadius="15" Direction="0" RenderingBias="Quality" ShadowDepth="1" Color="#FFBBBBBB"/>
                </Rectangle.Effect>
            </Rectangle>
            
            <Grid VerticalAlignment="Bottom" Margin="35,80" Height="240">
                <Label Content="登录" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="5" Foreground="Gray" FontSize="18"/>
                <StackPanel VerticalAlignment="Center" Margin="15">
                    <TextBox x:Name="Account" Margin="0,5" materialDesign:HintAssist.Hint="账号" Style="{StaticResource MaterialDesignFloatingHintTextBox}" FontFamily="Champagne &amp; Limousines" FontSize="16"/>
                    <PasswordBox x:Name="Password" Margin="0,5" materialDesign:HintAssist.Hint="密码" Style="{StaticResource MaterialDesignFloatingHintPasswordBox}" FontFamily="Champagne &amp; Limousines" FontSize="16"/>
                </StackPanel>
            </Grid>
    
            <Button Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,65" Content="LOGIN" Click="Login_Button"/>
    
            <TextBlock Text="注册账户" HorizontalAlignment="Left"  VerticalAlignment="Bottom" Margin="60 40" FontSize="13" Foreground="Gray"  Cursor="Hand" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown"/>
    
            <TextBlock Text="忘记密码?" HorizontalAlignment="Right " VerticalAlignment="Bottom" Margin="60 40"  FontSize="13" Foreground="Gray"  Cursor="Hand"/>
    
    
            <Button HorizontalAlignment="Right" VerticalAlignment="Top" Background="{x:Null}" BorderBrush="{x:Null}" Click="Close_Click" >
                <materialDesign:PackIcon Kind="Close"/>
            </Button>
    
            <Border CornerRadius="30" BorderBrush="#FF2281D1" BorderThickness="2" Width="100" Height="100" VerticalAlignment="Top" Margin="30">
                <Border.Background>
                    <ImageBrush ImageSource="./picture/Loginbackground.jpg"/>
                </Border.Background>
            </Border>
             
        </Grid>
    </Window>
    

    后台代码如下(LoginWindow.xaml.cs):

    using System;
    using System.Collections;
    using System.Windows;
    using System.Windows.Input;
    using Window = System.Windows.Window;
    
    namespace sample5
    {
        /// <summary>
        /// LoginWindow.xaml 的交互逻辑
        /// </summary>
        public partial class LoginWindow : Window
        {
            public string UserName;
            public string UserPassword;
            public int border = 1;
            public static Hashtable userall_harsh;
    
            public LoginWindow()
            {
                InitializeComponent();
            }
    
            private void MoveWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
                DragMove();
            }
    
            private void Close_Click(object sender, RoutedEventArgs e)
            {
                this.Close();
            }
    
    
            private void Login_Button(object sender, RoutedEventArgs e)
            {
                ExcelSave excel1 = new ExcelSave();
                userall_harsh = excel1.readExcel();
    
                if (userall_harsh == null)
                {
                    MessageBox.Show("无此账户,请先注册!");
                    return;
                }
                else
                {               
                    
                    IDictionaryEnumerator myEnumerator = userall_harsh.GetEnumerator();  //读取harshtable中的key和value值
                    while (myEnumerator.MoveNext()) //将枚举数推到集合的下一元素,若为空,则退出循环
                    {
    
                        UserName = myEnumerator.Key.ToString();         //key值赋给UserName
                        UserPassword = myEnumerator.Value.ToString();    //value值赋给UserPassword
    
                        if (Account.Text.ToString() == UserName && Password.Password.ToString() == UserPassword)
                        {
                            this.DialogResult = Convert.ToBoolean(1);
                            this.Close();
                            break;
                        }
                        else if (border<=userall_harsh .Count-1)      //给循环一边界,若循环到所存数据最后一个数仍然不正确,则执行else语句
                        {
                            border++;
                        }                        
                        else
                            MessageBox.Show("账号或密码错误,请重试!");
                    }
                }
            }
    
    
            //“注册账户”TextBlock触发事件
            private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
                RegisterWindow register1 = new RegisterWindow();  //Login为窗口名,把要跳转的新窗口实例化
                this.Close();  //关闭当前窗口
                register1.ShowDialog();   //打开新窗口          
            }
        }
    }
    
    

    3.注册界面设计

    Xaml代码如下:

    <Window x:Class="sample5.RegisterWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:sample5"
            mc:Ignorable="d"
            Title="用户登录" Height="500" Width="350" 
            ResizeMode="NoResize" 
            WindowStartupLocation="CenterScreen" 
            WindowStyle="None" 
            MouseLeftButtonDown="MoveWindow_MouseLeftButtonDown"
            FontFamily="Segoe UI Emoji">
        <Grid>
            <Rectangle Height="280" VerticalAlignment="Top">
                <Rectangle.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="#FF2281D1"/>
                        <GradientStop Color="#FF34268A" Offset="1"/>
                        <GradientStop Color="#FF33288B" Offset="0.546"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
            <Rectangle Height=" 220" VerticalAlignment="Bottom" >
                <Rectangle.Fill>
                    <SolidColorBrush Color="Snow" />
                </Rectangle.Fill>
            </Rectangle>
    
            <Rectangle Width="280" Height="240" VerticalAlignment="Bottom"  Margin="0,80" RadiusY="10" RadiusX="10" Fill="White" >
                <Rectangle.Effect>
                    <DropShadowEffect BlurRadius="15" Direction="0" RenderingBias="Quality" ShadowDepth="1" Color="#FFBBBBBB"/>
                </Rectangle.Effect>
            </Rectangle>
    
            <Grid VerticalAlignment="Bottom" Margin="35,80" Height="240">
                <Label Content="用户注册" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="5" Foreground="Black" FontSize="18"/>
                <StackPanel VerticalAlignment="Center" Margin="20">
                    <TextBox x:Name="Re_Account" Margin="0,5" materialDesign:HintAssist.Hint="请输入账号" Style="{StaticResource MaterialDesignFloatingHintTextBox}" FontFamily="Champagne &amp; Limousines" FontSize="16"/>
                    <PasswordBox x:Name="Re_Password" Margin="0,5" materialDesign:HintAssist.Hint="请输入密码" Style="{StaticResource MaterialDesignFloatingHintPasswordBox}" FontFamily="Champagne &amp; Limousines" FontSize="16"/>
                    <PasswordBox x:Name="Re_PasswordAgain" Margin="0,5" materialDesign:HintAssist.Hint="请确认密码" Style="{StaticResource MaterialDesignFloatingHintPasswordBox}" FontFamily="Champagne &amp; Limousines" FontSize="16"/>
                </StackPanel>
            </Grid>
    
            <Button Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,65" Content="Register" Click="Register_Button"/>
    
            <Border CornerRadius="30" BorderBrush="#FF2281D1" BorderThickness="2" Width="100" Height="100" VerticalAlignment="Top" Margin="30">
                <Border.Background>
                    <ImageBrush ImageSource="./picture/Registerbackground.jpg"/>
                </Border.Background>
            </Border>
    
            <Button HorizontalAlignment="Right" VerticalAlignment="Top" Background="{x:Null}" BorderBrush="{x:Null}" Click="ReClose_Click" >
                <materialDesign:PackIcon Kind="Close"/>
            </Button>
    
        </Grid>
    </Window>
    
    

    后台代码如下:

    using System;
    using System.Collections;
    using System.Windows;
    using System.Windows.Input;
    using Window = System.Windows.Window;
    
    
    namespace sample5
    {
        /// <summary>
        /// RegisterWindow.xaml 的交互逻辑
        /// </summary>
        public partial class RegisterWindow : Window
        {
    
            public static Hashtable userall;
            public RegisterWindow()
            {
                InitializeComponent();
            }
            private void MoveWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
                DragMove();
            }
    
            private void ReClose_Click(object sender, RoutedEventArgs e)
            {
                this.Close();
            }
    
            private void Register_Button(object sender, RoutedEventArgs e)
            {
                string u = Re_Account.Text.ToString();
                string p = Re_Password.Password.ToString();
                string rp = Re_PasswordAgain.Password.ToString();
                ExcelSave excel = new ExcelSave();
    
    
                if (String.IsNullOrEmpty(u))
                {
                    MessageBox.Show("user is not null");
                    return;
                }
                if (String.IsNullOrEmpty(p))
                {
                    MessageBox.Show("password is not null");
                    return;
                }
                if (String.IsNullOrEmpty(rp))
                {
                    MessageBox.Show("Repassword is not null");
                    return;
                }
                if (!p.Equals(rp))
                {
                    MessageBox.Show("password is not equals repassword");
                    return;
                }
    
                userall = excel.readExcel();  //读取excel数据
                if (userall == null)
                {
                    userall = new Hashtable();
                    userall.Add(u, p);
                }
                else
                {
                    bool isexist = userall.ContainsKey(u);  //判断用户是否存在
                    if (isexist)
                    {
                        MessageBox.Show("user is exist!");
                        return;
                    }
                    else
                    {
                        userall.Add(u, p);
                        Console.WriteLine(userall.Count);
                    }
                }
    
                System.Windows.Application.Current.Properties["users"] = userall;   //类似于Session的功能,用户登录后,可以将用户的信息保存在Properties中。
                excel.InsertExcel(u, p);
                MessageBox.Show("regist success!");
    
    
                MainWindow main = new MainWindow();
                main.WindowStartupLocation = WindowStartupLocation.Manual;   //使新窗口位置在原来的位置上
                main.Left = this.Left;  //使新窗口位置在原来的位置上
                main.Top = this.Top;  //使新窗口位置在原来的位置上
                this.Close();
                main.ShowDialog();  //打开新窗口         
            }
        }
    }
    
    

    4.Excel保存数据类设计

    学习使用Csharp处理excel表,创建ExcelSave.cs:

    using System;
    using Excel = Microsoft.Office.Interop.Excel;
    using System.Collections;
    using System.Windows;
    
    namespace sample5
    {
    
        public class ExcelSave
        {
            Excel.Application ExcelApp = new Excel.Application();
            #region 创建excel工作簿
            public void InsertExcel(string u, string p)
            {
                //1.创建Excel
    
                try
                {
                    //2.打开已经存在的工作簿
                    string path = "C:\\Users\\非黑不即白\\Desktop\\code.xlsx";
                    ExcelApp.Workbooks.Open(path, ReadOnly: false);
    
                    //3.
                    ExcelApp.Cells[1, 1].Value = "username";
                    ExcelApp.Cells[1, 2].Value = "password";
    
                    int RowCount = ExcelApp.ActiveSheet.UsedRange.Rows.Count + 1;
                    //ExcelApp.ActiveSheet.Rows[RowCount].Insert(u, p);
    
                    ExcelApp.Cells[RowCount, 1].Value = u;
                    ExcelApp.Cells[RowCount, 2].Value = p;
    
    
                    ExcelApp.DisplayAlerts = false; //保存Excel的时候,不弹出是否保存的窗口直接进行保存 
                    //4.保存工作表
                    ExcelApp.ActiveWorkbook.Save();
    
                }
                catch
                {
                    MessageBox.Show("导出文件保存失败,可能原因该文件已打开!", "警告!");
                }
                finally
                {
                    //5.关闭工作簿
                    ExcelApp.ActiveWorkbook.Close();
                    //6.退出excel
                    ExcelApp.Quit();
                    // PublicMethod.Kill(ExcelApp);
                }
    
            }
            #endregion
    
            #region 读取excel工作簿数据
            public Hashtable readExcel()
            {
                try
                {
                    //2.打开已经存在的工作簿
                    string path = "C:\\Users\\非黑不即白\\Desktop\\code.xlsx";
                    //ExcelApp.Workbooks.Open(path, ReadOnly: true);
                    Hashtable h = new Hashtable();
    
    
                    Excel.Workbook wb = ExcelApp.Application.Workbooks.Open(path, ReadOnly: true); //取得工作簿
                    Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);
    
                    int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行数
    
                    Excel.Range rng1 = ws.Cells.get_Range("A2", "A" + rowsint); // 取得数据范围区域(不包括标题列)
                    Excel.Range rng2 = ws.Cells.get_Range("B2", "B" + rowsint);
    
                    string[,] arry = new string[rowsint - 1, 2];  //将新值赋给一个数组
    
                    if (rowsint <= 1)
                    {
                        //MessageBox.Show("无账户信息,请先注册!");  LoginWindow已做判断,无需重复
                        return null;
                    }
                    else
                    {
                        if (rowsint == 2)  //解决表格有一个数据用户,再添加时报错的问题
                        {
                            arry[0, 0] = rng1.Value2.ToString();   //rng.value2获取单元格数据
                            arry[0, 1] = rng2.Value2.ToString();
                            h.Add(rng1.Value2.ToString(), rng2.Value2.ToString());
                            Console.WriteLine(rng1.Value2.ToString() + " :" + rng2.Value2.ToString());
                            return h;
                        }
                        else
                        {
                            for (int i = 1; i <= rowsint - 1; i++)
                            {
                                arry[i - 1, 0] = rng1.Value2[i, 1].ToString();   //rng.value2获取单元格数据
                                arry[i - 1, 1] = rng2.Value2[i, 1].ToString();
                                h.Add(rng1.Value2[i, 1].ToString(), rng2.Value2[i, 1].ToString());
                                Console.WriteLine(rng1.Value2[i, 1].ToString() + " :" + rng2.Value2[i, 1].ToString());
                            }
                            return h;
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("read excel error");
                    return null;
                }
                finally
                {
                    //5.关闭工作簿
                    ExcelApp.ActiveWorkbook.Close();
                    //6.退出excel
                    ExcelApp.Quit();
                    //PublicMethod.Kill(ExcelApp); //关闭excel后台进程,此处无需添加
                }
            }
            #endregion
        }
    
        /* 关闭excel后台进程
        public class PublicMethod
        {
            [DllImport("User32.dll", CharSet = CharSet.Auto)]
            public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
            public static void Kill(Excel.Application excel)
            {
                IntPtr t = new IntPtr(excel.Hwnd);//得到这个句柄,具体作用是得到这块内存入口 
    
                int k = 0;
                GetWindowThreadProcessId(t, out k);   //得到本进程唯一标志k
                System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);   //得到对进程k的引用
                p.Kill();     //关闭进程k
            }
        }*/
    }
    
    

    5.源码

    结构总览:
    在这里插入图片描述

    源码:点击跳转地址


    三、补充

    1.增加Mysql数据库存储账户数据

    using System;
    using System.Collections;
    using System.Windows;
    //引入MySQL
    using MySql.Data.MySqlClient;
    
    namespace SheepMusic
    {
        public class Mysql_Code
        {
            static string constring = "server = localhost ;port=3306; uid = root; pwd = djz19960824; database = test; charset=utf8;";   //定义连接mysql字符串
            MySqlConnection sqlCnn = new MySqlConnection(constring);    //连接mysql
    
            #region 读取Mysql数据库信息
            public Hashtable Mysql_read()
            {
                string username;
                string password;
                string cmdstring = "select * from code";    //写入sql
                MySqlCommand sqlCmd = new MySqlCommand(cmdstring, sqlCnn);   //创建命令对象  
                Hashtable h = new Hashtable();
    
                try
                {
                    sqlCnn.Open();  //打开数据库
                    MySqlDataReader rec = sqlCmd.ExecuteReader();
    
                    while (rec.Read())
                    {
                        username = rec.GetString(0);
                        password = rec.GetString(1);
                        h.Add(username, password);
                    }
                    return h;
    
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "error");
                    return null;
                }
                finally
                {
                    sqlCnn.Close();
                }
            }
            #endregion
    
            #region 外部写入Mysql数据库信息
            public void Mysql_insert(string u, string p)
            {
                try
                {
                    sqlCnn.Close();
                    sqlCnn.Dispose();
                    string insertstring = "insert into code values('" + u + "','" + p + "')";
                    MySqlCommand sqlInsert = new MySqlCommand(insertstring, sqlCnn);
                    sqlCnn.Open();
                    sqlInsert.ExecuteNonQuery();    //插入数据
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "error");
                }
                finally
                {
                    sqlCnn.Close();
                }
    
            }
            #endregion
    
            #region 修改Mysql数据库数据信息
            public void Mysql_reset(string u, string p)
            {
                try
                {
                    sqlCnn.Close();
                    sqlCnn.Dispose();
                    string resetstring = "update code set password ='" + p + "' where user = '" + u + "'";
                    MySqlCommand sqlReset = new MySqlCommand(resetstring, sqlCnn);
                    sqlCnn.Open();
                    sqlReset.ExecuteNonQuery();    //插入数据
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "error");
                }
                finally
                {
                    sqlCnn.Close();
                }
    
            }
            #endregion
        }
    }
    
    

    参考文献
    1. 少量代码设计一个登录界面 - .NET CORE(C#) WPF开发
    2.页面跳转
    3.WPF注册登录页面,同时将注册信息保存到一个excel中
    4.C#导出数据到Excel的几种方法
    补充学习

    展开全文
  • wpf 界面命令实例

    2018-05-09 08:46:20
    界面命令代替了Click事件,方便快捷实现界面交互,如果有数十种按钮,不需要每个按钮都实现一个函数
  • WPF对比WinForm实例

    2018-12-28 08:58:01
    WPF对比WinForm简单实例,这个例子主要展示同一个需求用WinForm和WPF分别进行实现,通过这个例子,我们可以看到两者之间的区别和联系,同时也可以对我们的项目选型带来一定的参考作用
  • WPF常用实例大全

    2017-12-13 12:46:57
    WPF常用实例大全 包含63个常用的WPF实例,包括RibbonStyle、MVVM、3D效果、基于插件式的开发框架、漂亮的WPF界面框架等等。。。。。。
  • 本文实例为大家分享了WPF定时刷新UI界面展示的具体代码,供大家参考,具体内容如下 代码: using NHibernate.Criterion; using System; using System.Collections.Generic; using System.Collections.ObjectModel; ...
  • C#WPF 刷新窗口 实例 可运行 http://www.cnblogs.com/leco/archive/2010/11/28/1890046.html WPF中实现Timer 事件 在 WPF 中不再有类似 WinForm 中的 Timer 控件,因此,需要使用 DispatcherTimer 类来实现类似 ...
  • WPF实例 360界面

    2014-10-02 01:47:17
    WPF 实例wpf开发,仿照360界面,新手学习好资料
  • WPF炫酷样式示例.rar

    2020-05-29 14:59:43
    WPF样式示例,可直接复制到项目中,包含各种控件样式,和滚动条,下拉条,按钮,单选框,对话框,进度条,日期格式,日期控件等等。
  • 最后启动wpf项目即可,运行结果:点击界面的按钮后如下,只要能成功在控制台显示"连接成功"即可。 如果不知道怎么启动后在控制台显示,参考我上篇文章的设置,很简单:...

    :wpf连接Oracle数据库有很多方法,这里先说明一种。

    1. 背景及版本说明

    vs版本:2017
    框架:.Net Framwork 4.5.2

    2. 步骤

    1. 首先,我们需要一个Oracle.ManagedDataAccess.dll 封装文件,这个文件的获取地址:http://xiazai.jb51.net/201908/yuanma/Oracle.ManagedDataAccess(jb51net).rar
    下载解压后找到里面的Oracle.ManagedDataAccess.dll文件,一会儿要用到

    2. 在自己的wpf项目中新建一个文件,我这里叫dll文件,把刚刚的Oracle.ManagedDataAccess.dll文件复制到这个文件夹下,如图所示。
    在这里插入图片描述
    然后右键wpf项目中的引用,选择“添加引用”,找到dll文件中的Oracle.ManagedDataAccess.dll,确定添加进来,添加后效果如下图
    在这里插入图片描述
    3. 然后在wpf项目里新添加一个类,添加方式如下图,我这里命名为MyOracleConnect,所以有了一个 MyOracleConnect.cs 文件
    在这里插入图片描述
    MyOracleConnect.cs 文件里的代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    //引入命名空间
    using Oracle.ManagedDataAccess.Client;
    using System.Data;
    
    namespace WpfApp1
    {
        class MyOracleConnect
        {
            //Oracle连接字符串
            private static string strconn = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));Persist Security Info=True;User ID=XXX;Password=XXXXXX;";
    
            public DataTable QueryDt(string sql)
            {
                using (OracleConnection conn = new OracleConnection(strconn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }
                        OracleDataAdapter adap = new OracleDataAdapter(sql, conn);
                        DataTable dt = new DataTable();
                        adap.Fill(dt);
                        Console.WriteLine("连接成功");
                        return dt;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("连接异常——>" + ex.Message);
                        return null;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
      }
    }
    
    

    注意里面绿色的这个代码 “Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));Persist Security Info=True;User ID=XXX;Password=XXXXXX;”,
    这里标红的5个地方是需要自己更改的,第一个是数据库的ip地址,我这里是本地电脑的数据库,所以写了localhost;第二个是端口号,第三个是服务器名,第四个是你Oracle的用户名,第五个是用户名对应的密码。

    4. MainWindow.xaml代码如下:

    <Window x:Class="WpfApp1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp1"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <StackPanel>
            <Button Name="button1" Content="从数据库读取数据并显示" Click="button1_Click" />
    
        </StackPanel>
    </Window>
    

    5. MainWindow.xaml.cs代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Data;
     
    namespace WpfApplication20190917D
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
     
            private List<Student> studentList;
     
            public MainWindow()
            {
                InitializeComponent();
            }
     
            private void button1_Click(object sender, EventArgs e)
            {
                string strSql = "select * from \"CUG_OPCTag\"";
                MyOracleConnect moc = new MyOracleConnect();
                DataTable dt = moc.QueryDt(strSql);
            }
        }
    }
    
    

    注意里面绿色的这个代码 “select * from “CUG_OPCTag””;", 这句话是sql语句,
    这里标的 CUG_OPCTag,是我自己数据库里的一张表格,你自己数据库有什么表,就写一个表名就行,注意,Oracle调用表名时的sql语句,表名要用双引号。

    6. 最后启动wpf项目即可,运行结果:点击界面的按钮后如下,只要能成功在控制台显示"连接成功"即可。
    如果不知道怎么启动后在控制台显示,参考我上篇文章的设置,很简单:https://blog.csdn.net/weixin_43604867/article/details/108077096
    最后结果如图
    在这里插入图片描述
    即最后连接成功。

    注:这只是其中一种用了Oracle.ManagedDataAccess.dll文件的方法,但是还有用其他dll文件的方法,一样可以连接。

    展开全文
  • WPF缓存实例

    2016-05-18 14:48:09
    WPF缓存实例
  • WPF登录跳转

    2021-01-07 20:33:32
    WPF登录跳转新建一个登录窗口,实现登录跳转 新建一个登录窗口,实现登录跳转 第一步:新建wpf窗口,命名为LoginWindow 第二步:按如下方式修改LoginWindow.xaml,设计登录窗体 <Window x:Class="wpfbase.Login...
  • WPF多页面Page导航实例

    2019-03-21 11:40:53
    这是一个通过WPF Frame控件实现多个Page之间的导航功能实例
  • 里面包含一些资源:...WPF界面下的会员登录.rar WPF动态添加行列DATAGRID.rar WpfApplication1.zip WPF.MDI.rar wpf-treeview.zip MVVM.rar WPF中UserControl如何访问它所属的Window的控件或事件.txt TabControl.zip
  • WPF 窗口单实例

    2019-09-03 23:02:44
     Mutex mutex = new Mutex(true, "单实例程序", out bool isNewInstance);  if (isNewInstance != true)  {  IntPtr intPtr = FindWindowW(null, "单实例窗口");  if (intPtr != IntPtr.Zero)  {  ...
  • WPF学习

    万次阅读 多人点赞 2019-03-05 22:00:17
    首先感谢刘铁锰先生的《深入浅出WPF》,学习WPF过程碰上很多新概念,如Data Binding、路由事件,命令、各种模板等。 WPF:编写CS端的UI技术。 怎么去掉WPF窗体靠上多出黑色的长条?在vs界面的菜单栏点击调试-选项...
  • InitializeComponent(); if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))return; // your code, eg viewModel 参考资料: WPF: Tips - Designer Detection
  • 本文档具体介绍了快速设计一个简单WPF串口上位机界面的实现过程和代码
  • WPF开发教程 ----WPF C# 编程 界面开发(很不错)

    千次下载 热门讨论 2010-07-25 18:54:00
    WPF开发教程.rar 目录 WPF基础入门 3 1. WPF基础之体系结构 3 2. WPF基础之XAML 9 3. WPF基础之基元素 23 4. WPF基础之属性系统 26 5. WPF基础之路由事件 33 6. WPF基础之布局系统 46 7. WPF基础之样式设置和模板化...
  • WPF高仿360卫士9.0界面设计_8409055 WPF呼吸闪烁效果例子_8434069 WPF摄影系统完整例子[按钮、浏览、菜单、样式]_8434083 WPF实现超酷样式按钮_8318169 WPF拖拽缩放等例子UIOperationDemo_8416813 WPF自定义控件开发...
  • WPF mediaplayer开发实例

    2014-12-31 15:05:31
    本代码包含MEDIAPLAYER的常用功能,包括播放、停止、下一个、上一个、播放列表等。如果要求不高,直接可以做软件的播放器使用,而且界面相对比较好。欢迎大家下载。
  • WPF实现VS界面效果

    2020-05-04 17:16:57
    写工具的时候,为了界面好看,实现类似于VS那样可以拖拽拉大拉小各个控件的效果,搜了一下,简单的说一下两种实现方法: 1.最简单的下载devexpress控件,LZ用的是15.1的版本,装好了左边工具栏会多一个 ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 7,651
精华内容 3,060
关键字:

wpf登录界面实例