在這種情況下,我會使用附加的行爲,它允許在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
。