【问题标题】:DialogService pass Object as parameter in ShowDialogDialogService 在 ShowDialog 中将 Object 作为参数传递
【发布时间】:2021-10-04 14:36:29
【问题描述】:

我想在 Prism WPF 中打开一个对话框。在我的 ViewModel 中执行一个名为 ExecuteOpenDialog 的命令,它会得到一个名为 soItemCommandParameter。我想将此参数传递给我的对话框。

private void ExecuteOpenDialog(SOItem soItem)
{
    System.Diagnostics.Debug.WriteLine(soItem.Name);
    ShowDialog(soItem);
}

看起来DialogParameters 只是strings?对吗?

private void ShowDialog(SOItem soItem)
{
    var message = msg;
    //using the dialog service as-is
    _dialogService.ShowDialog(typeof(DialogWindow).Name, new DialogParameters(soItem), r =>
    {
        if (r.Result == ButtonResult.None)
            Title = "Result is None";
        else if (r.Result == ButtonResult.OK)
            Title = "Result is OK";
        else if (r.Result == ButtonResult.Cancel)
            Title = "Result is Cancel";
        else
            Title = "I Don't know what you did!?";
    });
}

知道如何将我的SOItem 作为参数传递给我的对话框吗?

【问题讨论】:

    标签: c# wpf mvvm dialog prism


    【解决方案1】:

    首先,创建一个DialogParameters 实例并使用Add 方法添加带有密钥的soItem。构造函数DialogParameters 是一个查询,您只能在其中添加字符串值。

    private void ShowDialog(SOItem soItem)
    {
       var message = msg;
       //using the dialog service as-is
       var dialogParameters = new DialogParameters();
       dialogParameters.Add("MyItem", soItem);
    
       _dialogService.ShowDialog(typeof(DialogWindow).Name, dialogParameters, r =>
       {
          if (r.Result == ButtonResult.None)
             Title = "Result is None";
          else if (r.Result == ButtonResult.OK)
             Title = "Result is OK";
          else if (r.Result == ButtonResult.Cancel)
             Title = "Result is Cancel";
          else
             Title = "I Don't know what you did!?";
       });
    }
    

    或者,您可以使用集合初始化器来添加键值对。

    var dialogParameters = new DialogParameters
    {
       {"MyItem", soItem}
    };
    

    在您的对话框视图模型中实现IDialogAware 接口。打开对话框时会触发OnDialogOpened 覆盖。在那里,您可以使用索引器 parameters["MyItem"](返回 object)或通用 GetValue<T> 方法获取对话框参数,并将项目转换为所需的类型。

    public class MyDialogViewModel : BindableBase, IDialogAware
    {
    
       // ...other code, overrides, properties.
    
       private SOItem _soItem;
       public SOItem SOItem
       {
          get => _soItem;
          set => SetProperty(ref _soItem, value);
       }
    
       public virtual void OnDialogOpened(IDialogParameters parameters)
       {
          SOItem = parameters.GetValue<SOItem>("MyItem");
       }
    }
    

    【讨论】:

    • 太棒了!谢谢你。这正是我正在寻找的。我在ScrollViewer 中有一个ItemsControl。我的DataTemplate 是一个自定义控件,它有按钮。那些打开对话框的按钮,我正在为对话框发送实际点击的SOItem
    猜你喜欢
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 2015-12-09
    相关资源
    最近更新 更多