【问题标题】:Handling the "X" close button in WPF under MVVM在 MVVM 下处理 WPF 中的“X”关闭按钮
【发布时间】:2010-07-03 03:00:19
【问题描述】:

我正在 WPF 中创建一个基本的数据库应用程序,并且我已经开始使用 MVVM 模式。

我有一个对话框,要求用户从ListBox 中选择一个项目,然后单击“确定”。之后,我从视图模型中的属性中获取用户单击的项目并将其传递到另一个对话框。但是如果用户单击“取消”,我将该值设置为null,并且该操作被取消:我不打开下一个对话框并返回到主屏幕。示例:

public class SelectEquipmentViewModel : WorkspaceViewModel
{
    private bool _selected;

    public Equipment SelectedEquipment
    {
        // Item selected by the user
    }

    // Action for "SelectCommand," which is attached to
    // the "Select" button in the view
    public void ExecuteSelect()
    {
        _selected = true;

        // Fires a RequestClose event in WorkspaceViewModel,
        // which is attached to the view's Close method
        RequestClose();
    }

    public override void RequestClose()
    {
        if (!_selected)
        {
            // The user clicked "Cancel"
            SelectedEquipment = null;
        }

        base.RequestClose();
    }
}

这一直很好用,但是如果用户单击窗口控制框中的红色“X”关闭按钮,就会出现问题。 RequestClose 方法永远不会被调用,并且所选项目没有设置为 null,这很糟糕。

我考虑将视图模型附加到视图的 Closing 事件,但我觉得如果我开始为所有这些事件创建处理程序,这可能会变得混乱。

处理这种情况的“首选”方式是什么?

谢谢。

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    我认为使用 EventToCommand 行为将 Window 对象的 Closing 事件连接到新的 ExecuteCancel 命令是非常干净的。

    public void ExecuteCancel() 
    { 
        _selected = false; 
    
        // Fires a RequestClose event in WorkspaceViewModel, 
        // which is attached to the view's Close method 
        RequestClose(); 
    }
    

    你认为这会在哪里变得混乱?如果添加一个取消按钮,它可以使用相同的 ExecuteCancel 位...

    【讨论】:

    • 据我所知,这是在 M-V-VM 中执行此操作的最佳方法。在某些情况下,您仍然需要在代码隐藏类中添加一些逻辑,就像您讨厌使用 M-V-VM 那样做。
    【解决方案2】:

    行为是当用户使用 MVVM 在窗口上按下“X”按钮时您想要用来执行命令的。在此处查看 Reed Copsey 的博客:http://reedcopsey.com/2009/10/09/using-behaviors-to-allow-the-viewmodel-to-manage-view-lifetime-in-m-v-vm/

    您可以下载示例应用程序here...

    我一直使用这种方法来让 ViewModel 管理视图的生命周期。

    【讨论】:

      【解决方案3】:

      文章Handling a Window's Closed and Closing events in the View-Model 中描述了没有其他依赖项的方法,并提供了带有示例的代码。这不会在 xaml 后面添加代码。

      (感谢 Reed Copsey 的link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-08
        • 1970-01-01
        • 2013-06-27
        • 2013-07-03
        • 2020-11-13
        • 1970-01-01
        • 1970-01-01
        • 2013-12-11
        相关资源
        最近更新 更多