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

本文关键字:依赖 属性 窗口 代码 创建 | 更新日期: 2023-09-27 18:17:05

我有一个依赖属性,用于指定是否可以使用Escape键关闭窗口。我这样使用它:

    <Window x:Class="xxxx.xxxx.Client.View.AboutView"
        ...
    xmlns:utilities="clr-namespace:xxxx.xxxx.Client.Utilities"
    utilities:WindowUtilities.CloseOnEscape="True"
        ...
    </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();
        }
    }
}

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

try this:

WindowUtilities.GetCloseOnEscape(this);.

同样,您也可以使用SetCloseOnEscape