我有一个WPF应用程序,我正在尝试遵守MVVM模式规则。我的一个视图包含按钮:
<Button
Command="{Binding BrowseCommand}"
Margin="50,0"
Style="{StaticResource CommonButtonStyle}"
Width="100"
Height="30">
<TextBlock
Text="Browse"/>
</Button>
按钮命令调用方法:
private void Browse(object sender)
{
DialogService.BrowseForDestinationPath(DestinationPath);
}
此方法的主要目的是显示“选择目录对话框”,收集数据并将其返回到视图模型。
public static class DialogService
{
public static event action<string> FolderBrowseRequested;
...
public static void BrowseForDestinationPath(string initialPath)
{
FolderBrowseRequested?.Invoke(initialPath);
}
}
调用我的DialogService类中定义的事件,并且触发位于对话框代码后面的订户方法:
protected void OnFolderBrowseRequested(string initialPath)
{
string destinationPath = initialPath;
var browsingDialog = new VistaFolderBrowserDialog();
if(browsingDialog.ShowDialog(this).GetvalueOrDefault())
{
destinationPath = browsingDialog.SelectedPath;
var dataContext = DataContext as UnpackArchiveWindowViewModel;
if (dataContext != null)
dataContext.DestinationPath = destinationPath;
}
DialogService.FolderBrowseRequested -= OnFolderBrowseRequested; //so dumb
}
问题是我真的不喜欢这种解决方案,我坚信它是不必要的复杂和不雅观的。如何在单击按钮时正确显示对话框,收集一些数据并将其交付给我们的视图模型?我想将View和ViewModel分开,并完全尊重MVVM机制。