打开文件对话框在Prism MVVM中的使用

3

我正在使用Prism 6.1实现MVVM模式。对于通知/确认对话框,我使用InteractionRequest和InteractionRequest来详细介绍了msdn上的高级MVVM场景使用Prism库页面。我的问题是如何在MVVM中开始使用OpenFileDialog。Prism没有为保存和打开对话框提供类似的功能。您能否给我一个应该在View和ViewModel中合并的代码示例。谢谢。

2个回答

7

您只需要创建一个对话服务。

public interface IDialogService
{
    void Show();
}

public class DialogService : IDialogService
{
    public void Show()
    {
        //logic to show your dialogs
    }
}

请确保在容器中注册它:

Conatiner.Register<IDialogService, DialogService>( do you want a singletone?);

然后在你的构造函数中请求它。

public ViewAViewModel(IDialogService ds) { ... }

现在可以随时调用它。

嗨,Brian,我是你的忠实粉丝!在与VM交换消息时,我需要在View中键入任何代码吗?类似于与VM中的NotificationRequest属性绑定的InteractionRequestTrigger(在View中)?并且我是否总是需要使用中介者模式以及对话框服务?谢谢。 - sophon234
1
不确定您的意思。如果您只想使用服务显示对话框,请公开一个命令,在执行中调用dialogService.Show。 - user5420778
2
如果我错了,请纠正我。我认为所有的消息和对话框都应该由UI层处理?例如,当VM需要显示一个消息框时,我所需要做的就是从VM中引发一个事件,这将触发UI层(视图)中的InteractionRequestTrigger。但是现在,如果我需要从VM中显示一个打开的对话框,我只需从VM中调用dialogService.Show()。也就是说,在这里,VM与VIew之间没有交互,VM只是使用服务来显示打开的对话框,对吗?谢谢。 - sophon234
1
你错了 :). 只要使用接口来抽象实际实现,你就可以从虚拟机中显示任何对话框。 - user5420778

0

我个人会为此使用专用的TriggerAction。

public class SelectFileAction : TriggerAction<FrameworkElement>
{
    protected override void Invoke( object parameter )
    {
        ISelectFilePayload payload = notification.Content as ISelectFilePayload;

        // Configure the open file dialog
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.Filter = payload.Filter;

        // Show the dialog 
        Nullable<bool> result = dlg.ShowDialog();

        // Process dialog result
        if (result == true)
        {
            // Return the name of the selected file in the payload
            payload.Path = dlg.FileName;

            // The Callback property, if set, contains the invoker's callback method
            var callback = args.Callback;

            // Call the invoker's callback if any
            if (callback != null)
            {
                callback();
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接