prism WPF 登录对话框登录成功后显示主界面

发布于:2025-04-05 ⋅ 阅读:(21) ⋅ 点赞:(0)

prism WPF 登录对话框登录成功后显示主界面

项目结构

LoginUC.xaml

<UserControl x:Class="PrismWpfApp.Views.LoginUC"
             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" 
             xmlns:local="clr-namespace:PrismWpfApp.Views"
             xmlns:helper="clr-namespace:PrismWpfApp.Helper"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800" >
    <UserControl.Resources>
        <ControlTemplate TargetType="Button" x:Key="CloseButtonTemplate">
            <Grid Background="Transparent" Name="back">
                <TextBlock Text="&#xe653;" 
                   FontFamily="{DynamicResource iconfont}" VerticalAlignment="Center" HorizontalAlignment="Center"
                   FontSize="14"/>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="#DDD" TargetName="back"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>

        <Style TargetType="TextBox" x:Key="UsernameTextBoxStyle">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TextBox}">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" 
                            BorderThickness="{TemplateBinding BorderThickness}" 
                            Background="{TemplateBinding Background}" 
                            SnapsToDevicePixels="True"
                            CornerRadius="5">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="40"/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <Border BorderBrush="#DDD" BorderThickness="0,0,1,0" Margin="0,8,5,8"/>
                                <TextBlock Text="请输入用户名" Grid.Column="1" VerticalAlignment="Center" Foreground="#BBB"
                       Name="markText" Visibility="Collapsed" FontSize="12" Margin="2,0"/>
                                <TextBlock Text="&#xe610;"
                                   FontFamily="{DynamicResource iconfont}" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center"
                                   Foreground="#DDD"/>
                                <ScrollViewer x:Name="PART_ContentHost" Focusable="false"
                                          HorizontalScrollBarVisibility="Hidden" 
                                          VerticalScrollBarVisibility="Hidden"
                                          Grid.Column="1"
                                          VerticalAlignment="Center" MinHeight="20"/>
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Opacity" TargetName="border" Value="0.56"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="#FF7EB4EA"/>
                            </Trigger>
                            <Trigger Property="IsKeyboardFocused" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
                            </Trigger>
                            <DataTrigger Binding="{Binding Path=Text,RelativeSource={RelativeSource Mode=Self}}" Value="">
                                <Setter Property="Visibility" TargetName="markText" Value="Visible"/>
                            </DataTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <Style x:Key="PasswordBoxStyle" TargetType="{x:Type PasswordBox}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type PasswordBox}">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" 
                            BorderThickness="{TemplateBinding BorderThickness}" 
                            Background="{TemplateBinding Background}" 
                            SnapsToDevicePixels="True"
                            CornerRadius="5">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="40"/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <Border BorderBrush="#DDD" BorderThickness="0,0,1,0" Margin="0,8,5,8"/>
                                <TextBlock Text="请输入密码" Grid.Column="1" VerticalAlignment="Center" Foreground="#BBB"
                                   Name="markText" Visibility="Collapsed" FontSize="12" Margin="2,0"/>
                                <TextBlock Text="&#xe602;" FontFamily="{StaticResource iconfont}" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center"
                                       Foreground="#DDD"/>
                                <ScrollViewer x:Name="PART_ContentHost" Focusable="false"
                                          HorizontalScrollBarVisibility="Hidden" 
                                          VerticalScrollBarVisibility="Hidden"
                                          Grid.Column="1"
                                          VerticalAlignment="Center" MinHeight="20"/>
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Opacity" TargetName="border" Value="0.56"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="#FF7EB4EA"/>
                            </Trigger>
                            <Trigger Property="IsKeyboardFocused" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
                            </Trigger>
                            <DataTrigger Binding="{Binding Path=UserModel.Password}" Value="">
                                <Setter Property="Visibility" TargetName="markText" Value="Visible"/>
                            </DataTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsInactiveSelectionHighlightEnabled" Value="true"/>
                        <Condition Property="IsSelectionActive" Value="false"/>
                    </MultiTrigger.Conditions>
                    <Setter Property="SelectionBrush" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightBrushKey}}"/>
                </MultiTrigger>
            </Style.Triggers>
        </Style>

    </UserControl.Resources>
    <UserControl.Triggers>
        <EventTrigger RoutedEvent="Window.Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Duration="0:0:0.5" To="0" 
                             Storyboard.TargetName="tt"
                             Storyboard.TargetProperty="X"/>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </UserControl.Triggers>
    <Grid Width="740" Margin="5" Background="Transparent" MouseLeftButtonDown="Grid_MouseLeftButtonDown" >
        <Border Background="#F7F9FA" Margin="0,6" HorizontalAlignment="Right" Width="330" BorderBrush="#DDD" BorderThickness="0"
        CornerRadius="0,5,5,0">
            <Border.Effect>
                <DropShadowEffect Color="Black" ShadowDepth="0" Direction="0" BlurRadius="10" Opacity="0.2"/>
            </Border.Effect>
            <Border.RenderTransform>
                <TranslateTransform X="-350" x:Name="tt"/>
            </Border.RenderTransform>
            <Grid HorizontalAlignment="Right" Width="230" Margin="30,30,30,10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="100"/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition Height="60"/>
                    <RowDefinition Height="auto" MinHeight="40"/>
                </Grid.RowDefinitions>
                <StackPanel VerticalAlignment="Center" Margin="0,0,0,30">
                    <TextBlock Text="XX公司" Foreground="#333" FontSize="22"/>
                    <TextBlock Text="专注于提升工业智能管理协作平台" FontSize="12" Foreground="#888" Margin="0,10,0,0"/>
                </StackPanel>

                <ComboBox Grid.Row="1" Height="35" Margin="0,8" 
                      FontSize="14"
                      ItemsSource="{Binding DataList}"
                      DisplayMemberPath="Name"
                      SelectedValuePath="Id"
                      SelectedItem="{Binding SelectUser, Mode=TwoWay}"/>
                <PasswordBox Grid.Row="2" Height="35" Margin="0,8" Style="{StaticResource PasswordBoxStyle}"
                     helper:PasswordBoxHelper.Attach="true"
                     helper:PasswordBoxHelper.Password="{Binding SelectUser.Password,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                     FontSize="14"/>
                <!--<PasswordBox Grid.Row="2" Height="35" Margin="0,8" Style="{StaticResource PasswordBoxStyle}"
     FontSize="14"/>-->

                <Button Content="登    录" Background="#FF104991" Foreground="White" Grid.Row="4" Height="30" Margin="0,8" BorderThickness="0" VerticalAlignment="Top"
                Command="{Binding LoginCommand}" 
                CommandParameter="{Binding Path=.,RelativeSource={RelativeSource AncestorType=Window}}"/>
                <!--<Button Content="登    录" Background="#FF104991" Foreground="White" Grid.Row="4" Height="30" Margin="0,8" BorderThickness="0" VerticalAlignment="Top"
                Command="{Binding LoginCommand}" 
                CommandParameter="{Binding ElementName=win}"/>-->

                <!--关闭按钮-->
                <Button VerticalAlignment="Top" HorizontalAlignment="Right" Content="X" Margin="0,-30,-25,0"
                Template="{StaticResource CloseButtonTemplate}" 
                Width="40" Height="30"
                Command="{Binding CloseCommand}" 
                CommandParameter="{Binding Path=.,RelativeSource={RelativeSource AncestorType=Window}}"/>

                <TextBlock Text="{Binding ErrorMsg}" Foreground="Red" TextWrapping="Wrap" Grid.Row="10"
                   TextAlignment="Center"/>
            </Grid>
        </Border>

        <!--图片-->
        <Polygon Points="0 0,420 0,450 200 420 400 0 400" HorizontalAlignment="Left">
            <Polygon.Fill>
                <!--Viewbox 设置图片显示的位置-->
                <ImageBrush ImageSource="pack://application:,,,/PrismWpfApp;component/Asset/Images/login_image.jpg" 
                        Stretch="UniformToFill" Viewbox="0,0,1.4,1">
                </ImageBrush>
            </Polygon.Fill>
            <Polygon.Effect>
                <!--设置阴影 ShadowDepth 设置偏移量10-->
                <DropShadowEffect Color="Black" ShadowDepth="0" Direction="0" BlurRadius="10" Opacity="0.5"/>
            </Polygon.Effect>
        </Polygon>
        <Polygon Points="0 0,420,0,450 200 420 400 0 400" Opacity="0.2" StrokeThickness="0" Stroke="White" HorizontalAlignment="Left">
            <Polygon.Fill>
                <RadialGradientBrush>
                    <GradientStop Color="#22FFFFFF" Offset="0"/>
                    <GradientStop Color="#FF1B283C" Offset="1"/>
                    <GradientStop Color="#C6555F6E" Offset="0.617"/>
                </RadialGradientBrush>
            </Polygon.Fill>
        </Polygon>
    </Grid>
</UserControl>

LoginUCViewModel.cs

using Prism.Commands;
using Prism.Services.Dialogs;
using PrismWpfApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace PrismWpfApp.ViewModels
{
    public class LoginUCViewModel : UiViewModelBase, IDialogAware
    {
        public LoginUCViewModel()
        {
            this.SystemTitle = "登录-XX系统";
            DataList.Clear();
            var user1 = new UserInfoModel()
            {
                Id = 1,
                Name = "操作员",
                Password = ""
            };
            DataList.Add(user1);
            SelectUser = user1;
            DataList.Add(new UserInfoModel()
            {
                Id = 2,
                Name = "工程师",
                Password = ""
            });
            DataList.Add(new UserInfoModel()
            {
                Id = 1,
                Name = "管理员",
                Password = ""
            });
        }

        public List<UserInfoModel> DataList { get; set; } = new List<UserInfoModel>();

        //选择的用户
        private UserInfoModel _selectUser;
        /// <summary>
        /// 选择的用户
        /// </summary>
        public UserInfoModel SelectUser
        {
            get
            {
                return _selectUser;
            }
            set
            {
                SetProperty(ref _selectUser, value);
            }
        }

        //public string UserName { get; set; } = "admin";

        //public string Password { get; set; } = "123456";


        private string _errorMsg;

        public string ErrorMsg
        {
            get
            {
                return _errorMsg;
            }
            set
            {
                _errorMsg = value;
                SetProperty(ref _errorMsg, value);
            }
        }

        /// <summary>
        /// 登录命令
        /// </summary>
        public DelegateCommand LoginCommand
        {
            get
            {
                return new DelegateCommand(()=>
                {
                    var a = SelectUser;
                    //var b = Password;
                    //执行登录验证
                    RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
                });
            }
        }

        public string Title => "登录-XX系统";

        /// <summary>
        /// 关闭 委托
        /// </summary>
        public event Action<IDialogResult> RequestClose;

        /// <summary>
        /// 是否能关闭对话框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool CanCloseDialog()
        {
            return true;
        }

        /// <summary>
        /// 关闭后要处理的逻辑
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void OnDialogClosed()
        {
            //关闭也可以传参数(但一般不这么做)
            DialogParameters pairs = new DialogParameters();
            pairs.Add("Result", 0);

            //RequestClose 不为null时执行
            RequestClose?.Invoke(new DialogResult(ButtonResult.No, pairs));

            //两种方法等效
            //if (RequestClose != null)
            //{
            //    RequestClose.Invoke(new DialogResult(ButtonResult.No));
            //}
        }

        /// <summary>
        /// 打开对话框前的处理逻辑
        /// </summary>
        /// <param name="parameters"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnDialogOpened(IDialogParameters parameters)
        {
            //if (parameters.ContainsKey("Msg"))
            //{
            //    Msg = parameters.GetValue<string>("Msg");
            //}
            //if (parameters.ContainsKey("UserId"))
            //{
            //    UserId = parameters.GetValue<string>("UserId");
            //}
        }
    }
}

注册 对话框服务并重写初始化方法

App.xaml.cs 

using Prism.Ioc;
using Prism.Modularity;
using Prism.Services.Dialogs;
using Prism.Unity;
using PrismWpfApp.ViewModels;
using PrismWpfApp.Views;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace PrismWpfApp
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : PrismApplication
    {
        /// <summary>
        /// 提供主窗口的对象
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        protected override Window CreateShell()
        {
            //打开第一个窗口 ModuleWindow
            return Container.Resolve<MainWindow>();
            //return Container.Resolve<ModuleWindow>();
            //return Container.Resolve<LoginWindow>();
            //return new MainWindow();
        }

        /// <summary>
        /// 业务中所有需要注入的对象,在这个方法里注册
        /// </summary>
        /// <param name="containerRegistry"></param>
        /// <exception cref="NotImplementedException"></exception>
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            //注册 导航 RegisterForNavigation
            containerRegistry.RegisterForNavigation<UserControlA>();
            containerRegistry.RegisterForNavigation<UserControlB>();
            containerRegistry.RegisterForNavigation<UserControlC>();

            //注册 对话框服务
            containerRegistry.RegisterDialog<DialogView, DialogViewModel>();
            containerRegistry.RegisterDialog<LoginUC, LoginUCViewModel>();
        }

        /// <summary>
        /// 添加模块(代码引用)
        /// </summary>
        /// <param name="moduleCatalog"></param>
        //protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        //{
        //    moduleCatalog.AddModule<ModuleAProfile>();
        //    moduleCatalog.AddModule<ModuleBProfile>();
        //    base.ConfigureModuleCatalog(moduleCatalog);
        //}

        /// <summary>
        /// 创建模块
        /// </summary>
        protected override IModuleCatalog CreateModuleCatalog()
        {
            return new DirectoryModuleCatalog() { ModulePath = @".\Modules" };
        }

        //protected override void OnStartup(StartupEventArgs e)
        //{
        //    base.OnStartup(e);

        //    if (new LoginWindow().ShowDialog() == true)
        //    {
        //        new MainWindow().ShowDialog();
        //    }
        //    Application.Current.Shutdown();
        //}

        /// <summary>
        /// 重写 初始化 方法
        /// </summary>
        protected override void OnInitialized()
        {
            try
            {
                var dialogService = Container.Resolve<IDialogService>();
                //如果没有登录就打开登录对话框
                dialogService.ShowDialog("LoginUC", calback =>
                {
                    if (calback.Result != ButtonResult.OK)
                    {
                        Environment.Exit(0);
                        return;
                    }
                    base.OnInitialized();
                });
            }
            catch (Exception ex)
            {

            }
        }
    }
}