我有一个WPF应用程序,它在ViewModel中调用MessageBox.Show() (以检查用户是否真的想删除)。这实际上是可行的,但是违背了MVVM的原理,因为ViewModel不应该显式地决定视图上发生了什么。
因此,现在我正在考虑如何在应用程序中最好地实现MessageBox.Show()功能,选项:
和这两种解决方案似乎都过于复杂,对于过去使用MessageBox.Show()的几行代码来说是太复杂了。
以什么方式在您的MVVM应用程序中成功地实现了对话框?
发布于 2015-07-17 08:12:19
关于迪安·查尔克的回答,现在他的答案已经过时了:
在App.xaml.cs文件中,我们将确认对话框连接到视图模型。
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var confirm = (Func<string, string, bool>)((msg, capt) => MessageBox.Show(msg, capt, MessageBoxButton.YesNo) == MessageBoxResult.Yes);
var window = new MainWindowView();
var viewModel = new MainWindowViewModel(confirm);
window.DataContext = viewModel;
...
}
在视图(MainWindowView.xaml)中,有一个按钮在ViewModel中调用命令
<Button Command="{Binding Path=DeleteCommand}" />
视图模型(MainWindowViewModel.cs)使用委托命令来显示“您确定吗?”对话框并执行此操作。在本例中,它是一个类似于SimpleCommand
的这,但是ICommand的任何实现都应该这样做。
private readonly Func<string, string, bool> _confirm;
//constructor
public MainWindowViewModel(Func<string, string, bool> confirm)
{
_confirm = confirm;
...
}
#region Delete Command
private SimpleCommand _deleteCommand;
public ICommand DeleteCommand
{
get { return _deleteCommand ?? (_deleteCommand = new SimpleCommand(ExecuteDeleteCommand, CanExecuteDeleteCommand)); }
}
public bool CanExecuteDeleteCommand()
{
//put your logic here whether to allow deletes
return true;
}
public void ExecuteDeleteCommand()
{
bool doDelete =_confirm("Are you sure?", "Confirm Delete");
if (doDelete)
{
//delete from database
...
}
}
#endregion
https://stackoverflow.com/questions/1098023
复制相似问题