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

时间:2011-12-02 21:00:02

标签: c# wpf

我像这样创建了自己的依赖属性

    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属性,但不会尝试设置Visible属性

如何使它工作?

1 个答案:

答案 0 :(得分:1)

您不能在依赖项属性包装器中包含任何逻辑。 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包装器仅为您班级的消费者提供便利。