2014-03-07 95 views
3

創建像這樣一個窗口,用我的自定義UserControl的內容:從MVVM WPF中內容的ViewModel中關閉一個窗口?

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

我想打開Window作爲一個對話框,並得到結果:

var result = newCacheForm.ShowDialog(); 

我有到位的代碼綁定並將對話框設置爲true或false,但是如何關閉UserControl ViewModel中的窗口?如果這不能完成,我該如何以MVVM友好的方式工作?

回答

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的Click處理程序我說這種行爲是這樣的:

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; 
} 

當然,而不是應使用按鈕的處理程序。

整個項目可用here