Open File Dialog MVVM
Ok I really would like to know how expert MVVM developers handle an openfile dialog in WPF.
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
}
}
Because I believe that goes against MVVM methodology.
What do I do?
The best thing to do here is use a service.
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.
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
}
}
I would have liked to comment on one of the answers, but alas, my reputation is not high enough to do so.
Having a call such as OpenFileDialog() violates the MVVM pattern because it implies a view (dialog) in the view model. The view model can call something like GetFileName() (that is, if simple binding is not sufficient), but it should not care how the file name is obtained.
I use a service which i for example can pass into the constructor of my viewModel or resolve via dependency injection. eg
public interface IOpenFileService
{
string FileName { get; }
bool OpenFileDialog()
}
and a class implementing it, using OpenFileDialog under the hood. In the viewModel, i only use the interface and thus can mock/replace it if needed.
链接地址: http://www.djcxy.com/p/56118.html上一篇: 如何处理使用MVVM打开和关闭新窗口?
下一篇: 打开文件对话框MVVM