您可以为此编写扩展方法。
所以你有一个定义了附加属性的类(我们称之为 WindowExtensions)。
internal class WindowExtensions
{
public static readonly DependencyProperty WindowClosingCommandProperty = DependencyProperty.RegisterAttached(
"WindowClosingCommand", typeof (ICommand), typeof (WindowExtensions), new PropertyMetadata(null, OnWindowClosingCommandChanged));
private static void OnWindowClosingCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Window window = d as Window;
if (window == null)
return;
if (e.NewValue != null)
{
window.Closing += WindowOnClosing;
}
}
private static void WindowOnClosing(object sender, CancelEventArgs e)
{
Window window = sender as Window;
if (window == null)
return;
ICommand windowClosingCommand = GetWindowClosingCommand(window);
windowClosingCommand.Execute(e);
}
public static void SetWindowClosingCommand(DependencyObject element, ICommand value)
{
element.SetValue(WindowClosingCommandProperty, value);
}
public static ICommand GetWindowClosingCommand(DependencyObject element)
{
return (ICommand) element.GetValue(WindowClosingCommandProperty);
}
}
在 Window-Element 上的 XAML 中,您可以将附加属性映射到 ViewModel 中的 ICommand-Property,例如:
nameSpaceOfWindowExtensions:WindowExtensions.WindowClosingCommand="{Binding WindowClosingCommand}"
在您的 ViewModel 中,您有一个 ICommand-Property 可以处理它。
类似的东西:
private ICommand windowClosingCommand;
public ICommand WindowClosingCommand
{
get { return windowClosingCommand ?? (windowClosingCommand = new RelayCommand(OnWindowClosing)); }
}
private void OnWindowClosing(object parameter)
{
CancelEventArgs cancelEventArgs = parameter as CancelEventArgs;
if (cancelEventArgs != null)
{
// If you want to cancel the closing of the window you can call the following:
//cancelEventArgs.Cancel = true;
}
}
如果您不需要 ViewModel 中的 CancelEventArgs,只需修改附加属性中的以下行:
windowClosingCommand.Execute(e);
到
windowClosingCommand.Execute(null);