在MVVM WPF中,如何从其内容的ViewModel关闭一个窗口?

3
使用我的自定义作为内容,创建类似这样的窗口:
Window newCacheForm = new Window
{
    Title = "Add New Cache Tag",
    Content = new NewCacheControl()
};

我想将 Window 作为对话框打开并获取结果:

var result = newCacheForm.ShowDialog();

我已经编写了代码来绑定并将对话框设置为true或false,但是如何从 ViewModel关闭窗口?如果无法完成此操作,如何以MVVM友好的方式解决此问题?

1个回答

1
在这种情况下,我会使用一个“附加”行为,它允许在View的一侧使用独立的逻辑。我个人没有创建它,而是从这里获取并进行了一些补充 - 将Get()添加到依赖属性中。
以下是此行为的完整代码:
public static class WindowCloseBehaviour
{
    public static bool GetClose(DependencyObject target)
    {
        return (bool)target.GetValue(CloseProperty);
    }

    public static void SetClose(DependencyObject target, bool value)
    {
        target.SetValue(CloseProperty, value);
    }

    public static readonly DependencyProperty CloseProperty = DependencyProperty.RegisterAttached("Close",
                                                                                                  typeof(bool),
                                                                                                  typeof(WindowCloseBehaviour),
                                                                                                  new UIPropertyMetadata(false, OnClose));

    private static void OnClose(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue is bool && ((bool)e.NewValue))
        {
            Window window = GetWindow(sender);

            if (window != null)
                window.Close();
        }
    }

    private static Window GetWindow(DependencyObject sender)
    {
        Window window = null;

        if (sender is Window)
            window = (Window)sender;

        if (window == null)
            window = Window.GetWindow(sender);

        return window;
    }
}

在创建新的 Window 的点击处理程序中,我添加了以下行为:
private void Create_Click(object sender, RoutedEventArgs e)
{
    Window newCacheForm = new Window
    {
        Title = "Add New Cache Tag",
        Content = new TestUserControl(),
        DataContext = new TestModel() // set the DataContext
    };

    var myBinding = new Binding();                // create a Binding
    myBinding.Path = new PropertyPath("IsClose"); // with property IsClose from DataContext
    newCacheForm.SetBinding(WindowCloseBehaviour.CloseProperty, myBinding); // for attached behavior 

    var result = newCacheForm.ShowDialog();

    if (result == false) 
    {
        MessageBox.Show("Close Window!");
    }
}

UserControl 的 Close 处理程序中编写以下内容:
private void Close_Click(object sender, RoutedEventArgs e)
{
    TestModel testModel = this.DataContext as TestModel;
    testModel.IsClose = true;
}

自然而然的,应该使用命令来处理按钮,而不是为按钮使用Click处理程序。

整个项目在此处可用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接