在代码中创建 window 时使用依赖属性

Using dependency properties when window is created in code

我有一个依赖项 属性 用于指定是否可以使用 Escape 键关闭 window。我是这样使用的:

    <Window x:Class="xxxx.xxxx.Client.View.AboutView"
        ...
    xmlns:utilities="clr-namespace:xxxx.xxxx.Client.Utilities"
    utilities:WindowUtilities.CloseOnEscape="True"
        ...
    </Window>

但是,当在代码中创建 window 时,如何使用此依赖项 属性?这是一个例子:

    var window = new Window();

    var someView = new SomeView
    {
        DataContext = new SomeView()
    };
    window.Content = someView;
    return window.ShowDialog();

依赖项 属性 的代码如下所示:

public static class WindowUtilities
{
    public static readonly DependencyProperty CloseOnEscapeProperty = DependencyProperty.RegisterAttached(
        "CloseOnEscape",
        typeof (bool),
        typeof (WindowUtilities),
        new FrameworkPropertyMetadata(false, CloseOnEscapeChanged));

    public static bool GetCloseOnEscape(DependencyObject d)
    {
        return (bool) d.GetValue(CloseOnEscapeProperty);
    }

    public static void SetCloseOnEscape(DependencyObject d, bool value)
    {
        d.SetValue(CloseOnEscapeProperty, value);
    }

    private static void CloseOnEscapeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var target = d as Window;
        if (target != null)
        {
            if ((bool) e.NewValue)
                target.PreviewKeyDown += Window_PreviewKeyDown;
            else
                target.PreviewKeyDown -= Window_PreviewKeyDown;
        }
    }

    private static void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        var target = sender as Window;

        if (target != null)
        {
            if (e.Key == Key.Escape)
                target.Close();
        }
    }
}

试试这个:

WindowUtilities.GetCloseOnEscape(this);.

同样你可以使用SetCloseOnEscape