从MVVM WPF中的内容的ViewModel关闭一个窗口?

时间:2014-03-07 17:16:40

标签: c# wpf mvvm user-controls window

使用我的自定义UserControl作为内容创建一个这样的窗口:

Window newCacheForm = new Window
{
    Title = "Add New Cache Tag",
    Content = new NewCacheControl()
};

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

var result = newCacheForm.ShowDialog();

我有适当的代码绑定并将对话框设置为true或false,但是如何从UserControl ViewModel关闭Window?如果无法做到这一点,我该如何以MVVM友好的方式工作呢?

1 个答案:

答案 0 :(得分:1)

在这种情况下,我会使用附加行为,它允许在View一侧使用独立逻辑。我个人没有创建它,但是花了here并且很少补充 - 将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的关闭处理程序中写下这个:

private void Close_Click(object sender, RoutedEventArgs e)
{
    TestModel testModel = this.DataContext as TestModel;
    testModel.IsClose = true;
}

当然,应该使用命令来代替按钮的Click处理程序。

  

整个项目可用here

相关问题