prism-使用对话框(IDialogService)

  1. 主窗口创建按钮用于打开登录对话框

View

<Button Content="打开对话框" Command="{Binding OpenDialogCommand}" Margin="10" Width="100" Height="30"/>

ViewModel

public class MainViewModel : BindableBase
{
    public DelegateCommand OpenDialogCommand { get; private set; }
    
    private IDialogService dialog;

    public MainViewModel(IDialogService dialog)
    {
        OpenDialogCommand = new DelegateCommand(OpenLoginDialog);
        this.dialog = dialog;
    }

    void OpenLoginDialog()
    {
        //对话框打开时传递自定义参数
        DialogParameters parameters = new DialogParameters();
        parameters.Add("CurTime", $"{DateTime.Now.ToString()}");
    
        dialog.ShowDialog("LoginDialogView",parameters, result =>
        {
            if (result.Result == ButtonResult.OK)
            {
                //对话框关闭时返回的回调参数
                string userName = result.Parameters.GetValue<string>("userName");
                string passWord = result.Parameters.GetValue<string>("passWord");
                
                // 处理登录成功的逻辑
                MessageBox.Show("登录成功");
            }
            else if (result.Result == ButtonResult.Cancel)
            {
                // 处理取消登录的逻辑
                MessageBox.Show("取消登录");
            }
        });
    }
}
  1. 创建登录对话框

View

<UserControl x:Class="WpfDemo.Views.Dialogs.LoginDialogView"
             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:WpfDemo.Views.Dialogs"
             xmlns:prism="http://prismlibrary.com/"
             mc:Ignorable="d" 
            Height="450" Width="800">
    <prism:Dialog.WindowStyle>
        <Style TargetType="Window">
            <!--窗体屏幕居中显示-->
            <Setter Property="prism:Dialog.WindowStartupLocation" Value="CenterScreen"/>
            <!--禁止调整窗体尺寸-->
            <Setter Property="ResizeMode" Value="NoResize"/>
            <!--窗体的宽和高根据内容的大小设置-->
            <Setter Property="SizeToContent" Value="WidthAndHeight" />
        </Style>
    </prism:Dialog.WindowStyle>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <TextBlock Text="用户登录" 
                   FontWeight="Bold" 
                   FontSize="20"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   Margin="0,20"/>

        <StackPanel Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center">
            <StackPanel Orientation="Horizontal" 
                        HorizontalAlignment="Center"
                        Margin="0,0,0,15">
                <TextBlock Text="账号:" 
                           VerticalAlignment="Center"
                           Width="60"
                           TextAlignment="Center"/>
                <TextBox Text="{Binding UserName}"
                         Width="220"
                         Padding="8,2"
                         Margin="10,0,0,0"/>
            </StackPanel>

            <StackPanel Orientation="Horizontal" 
                        HorizontalAlignment="Center">
                <TextBlock Text="密码:" 
                           VerticalAlignment="Center"
                           Width="60"
                           TextAlignment="Center"/>
                <TextBox Text="{Binding Password}"
                         Width="220"
                         Padding="8,2"
                         Margin="10,0,0,0"/>
            </StackPanel>
        </StackPanel>

        <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,0,20,20">
            <Button Content="取消" Margin="0,0,10,0" Width="40" Height="25" Command="{Binding CancelCommand}" />
            <Button Content="确定" Width="40" Height="25" Command="{Binding LoginCommand}"/>
        </StackPanel>
    </Grid>
</UserControl>

ViewModel

 public class LoginDialogViewModel : BindableBase,IDialogAware
 {
     //窗口左上角标题
     public string Title { get; set; } = "登录";

     public event Action<IDialogResult> RequestClose;

     /// <summary>
     /// 用户名
     /// </summary>
     private string _userName;
     public string UserName
     {
         get { return _userName; }
         set { SetProperty(ref _userName, value); }
     }

     /// <summary>
     /// 密码
     /// </summary>
     private string _password;
     public string Password
     {
         get { return _password; }
         set { SetProperty(ref _password, value); }
     }

     /// <summary>
     /// 登录命令
     /// </summary>
     public DelegateCommand LoginCommand { get; private set; }

     /// <summary>
     /// 取消命令
     /// </summary>
     public DelegateCommand CancelCommand { get; private set; }

     public LoginDialogViewModel()
     {
         LoginCommand = new DelegateCommand(DoLoginCommand);
         CancelCommand = new DelegateCommand(DoCancelCommand);
     }

     public void DoLoginCommand()
     {
         DialogParameters userInfo = new DialogParameters();
         userInfo.Add("userName", UserName);
         userInfo.Add("passWord", Password);

         //关闭对话框并传递结果给调用者
         RequestClose.Invoke(new DialogResult(ButtonResult.OK, userInfo));
     }

     public void DoCancelCommand()
     {
         RequestClose.Invoke(new DialogResult(ButtonResult.Cancel));
     }

     /// <summary>
     /// 是否可以关闭该对话框
     /// </summary>
     /// <returns></returns>
     public bool CanCloseDialog()
     {
         return true;
     }

     /// <summary>
     /// 对话框关闭时执行逻辑
     /// </summary>
     public void OnDialogClosed()
     {
     }

     /// <summary>
     /// 对话框打开时执行逻辑
     /// </summary>
     /// <param name="parameters"></param>
     public void OnDialogOpened(IDialogParameters parameters)
     {
         if (parameters.ContainsKey("CurTime"))
         {
             string CurTime = parameters.GetValue<string>("CurTime");
         }
     }
 }
  1. 注册对话框视图及其对应的视图模型。
 public partial class App : PrismApplication
 {
     protected override Window CreateShell()
     {
         return Container.Resolve<MainView>();
     }

     protected override void RegisterTypes(IContainerRegistry containerRegistry)
     {
         containerRegistry.RegisterDialog<LoginDialogView, LoginDialogViewModel>();
     }
 }
  1. 调试运行

点击“打开对话框”按钮。

对话框ViewModel中 接收主窗体传递的参数CurTime

显示登录对话框

点击“取消”按钮

输入用户名和密码并点击“确定”按钮

主窗体接收登录对话框返回的回调参数。

posted @ 2025-05-03 09:44  相遇就是有缘  阅读(68)  评论(0)    收藏  举报