在这种情况下,我会使用一个“附加”行为,它允许在
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()
};
var myBinding = new Binding();
myBinding.Path = new PropertyPath("IsClose");
newCacheForm.SetBinding(WindowCloseBehaviour.CloseProperty, myBinding);
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
处理程序。
整个项目在此处可用。