首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在MVVM中成功地实现MessageBox.Show()功能?

如何在MVVM中成功地实现MessageBox.Show()功能?
EN

Stack Overflow用户
提问于 2009-07-08 13:19:12
回答 13查看 24.9K关注 0票数 47

我有一个WPF应用程序,它在ViewModel中调用MessageBox.Show() (以检查用户是否真的想删除)。这实际上是可行的,但是违背了MVVM的原理,因为ViewModel不应该显式地决定视图上发生了什么。

因此,现在我正在考虑如何在应用程序中最好地实现MessageBox.Show()功能,选项:

  1. 我可以在短信里留言“你确定.”连同两个按钮“是”和“否”,在我的XAML中的一个边框中创建一个触发器,以便根据名为AreYourSureDialogueBoxIsVisible,的ViewModelProperty折叠/可见,然后当我需要这个对话框时,将AreYourSureDialogueBoxIsVisible指定为"true",并通过DelegateCommand返回到my ViewModel中处理这两个按钮。
  2. 我还可以尝试用XAML中的触发器来处理这个问题,这样Delete按钮实际上只会出现一些边界元素,其中包含消息和按钮,而Yes按钮则执行实际删除操作。

这两种解决方案似乎都过于复杂,对于过去使用MessageBox.Show()的几行代码来说是太复杂了。

以什么方式在您的MVVM应用程序中成功地实现了对话框?

EN

Stack Overflow用户

发布于 2015-07-17 08:12:19

关于迪安·查尔克的回答,现在他的答案已经过时了:

在App.xaml.cs文件中,我们将确认对话框连接到视图模型。

代码语言:javascript
运行
复制
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中调用命令

代码语言:javascript
运行
复制
<Button Command="{Binding Path=DeleteCommand}" />

视图模型(MainWindowViewModel.cs)使用委托命令来显示“您确定吗?”对话框并执行此操作。在本例中,它是一个类似于SimpleCommand,但是ICommand的任何实现都应该这样做。

代码语言:javascript
运行
复制
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
票数 5
EN
查看全部 13 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1098023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档