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

原文: 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?;
        }));
}

场景2

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

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/10129760.html