将app属性绑定到自己的依赖属性

本文关键字:属性 自己的 依赖 绑定 app | 更新日期: 2023-09-27 18:16:26

我创建了自己的依赖属性

    public bool Visible
    {
        get
        {
            return (bool)GetValue(VisibleProperty);
        }
        set
        {
            System.Windows.Visibility v = value == true ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
            SetValue(VisibleProperty, value);
            border.Visibility = v;
        }
    }
    public static readonly DependencyProperty VisibleProperty = DependencyProperty.Register("Visible", typeof(bool), typeof(SpecialMenuItem), new UIPropertyMetadata(false));

我将我的app属性绑定到它,但运气不好。App属性(App .xaml.cs)和绑定:

    public bool IsGamePlaying
    {
        get
        {
            return isGamePlaying;
        }
        set
        {
            isGamePlaying = value;
        }
    }
    private bool isGamePlaying;
<my:SpecialMenuItem ... Visible="{Binding Path=IsGamePlaying, Source={x:Static Application.Current}}" />

当我在调试时,它读取IsGamePlaying属性,但不尝试设置可见属性

它是如何工作的?

将app属性绑定到自己的依赖属性

不能在依赖属性包装器中包含任何逻辑。WPF将在可能的情况下直接调用GetValue/SetValue,而不是使用CLR属性。您应该通过在依赖项属性中使用元数据来包含任何无关的逻辑。例如:

public static readonly DependencyProperty VisibleProperty = DependencyProperty.Register("Visible", typeof(bool), typeof(SpecialMenuItem), new FrameworkPropertyMetadata(false, OnVisibleChanged));
private static void OnVisibleChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
    // logic here will be called whenever the Visible property changes
}

CLR包装器仅仅是为了方便你的类的消费者。