打开文件对话框MVVM [英] Open File Dialog MVVM
问题描述
好吧,我真的很想知道MVVM专业开发人员如何在WPF中处理打开文件对话框.
Ok I really would like to know how expert MVVM developers handle an openfile dialog in WPF.
我真的不想在我的ViewModel中执行此操作(通过DelegateCommand引用浏览")
I don't really want to do this in my ViewModel(where 'Browse' is referenced via a DelegateCommand)
void Browse(object param)
{
//Add code here
OpenFileDialog d = new OpenFileDialog();
if (d.ShowDialog() == true)
{
//Do stuff
}
}
因为我认为这与MVVM方法背道而驰.
Because I believe that goes against MVVM methodology.
我该怎么办?
推荐答案
此处最好的做法是使用服务.
The best thing to do here is use a service.
服务只是您从中央服务存储库(通常是IOC容器)访问的类.然后,该服务将实现所需的功能,例如OpenFileDialog.
A service is just a class that you access from a central repository of services, often an IOC container. The service then implements what you need like the OpenFileDialog.
因此,假设您在Unity容器中有一个IFileDialogService
,则可以...
So, assuming you have an IFileDialogService
in a Unity container, you could do...
void Browse(object param)
{
var fileDialogService = container.Resolve<IFileDialogService>();
string path = fileDialogService.OpenFileDialog();
if (!string.IsNullOrEmpty(path))
{
//Do stuff
}
}
这篇关于打开文件对话框MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!