WPF通过附加属性控制窗口关闭

场景1

当使用 ShowDialog() 方式显示窗口时,通过定义附加属性的方式可实现在 ViewModel 中进行数据绑定(bool?)来控制子窗口的显示和关闭

public class ExWindow
{
    public static bool? GetDialogResult(DependencyObject obj)
    {
        return (bool?)obj.GetValue(DialogResultProperty);
    }

    public static void SetDialogResult(DependencyObject obj, bool value)
    {
        obj.SetValue(DialogResultProperty, value);
    }

    // Using a DependencyProperty as the backing store for DialogResult.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DialogResultProperty =
        DependencyProperty.RegisterAttached("DialogResult", typeof(bool?), typeof(ExWindow), new PropertyMetadata(true, (d, e) =>
        {
            var handler = d as Window;
            handler.DialogResult = e.NewValue as bool?;
        }));
}
  • 参考地址:
    • Getting “DialogResult can be set only after Window is created and shown as dialog” when implementing WPF MVVM pattern for form closing
    • DialogResult can be set only after Window is created and shown as dialog

场景2

当主窗口的显示和关闭也想通过在 ViewModel 中来进行控制的话可以通过事件和消息级制来实现,具体可参考 MVVM Light 中的 Messenger 使用方式

转载于:https://www.cnblogs.com/hippieZhou/p/9898258.html

你可能感兴趣的:(WPF通过附加属性控制窗口关闭)