deha
deha

Reputation: 815

binding app property to own dependency property

I made own dependency property like this

    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));

I'm binding my app property to it, but no luck. App property(app.xaml.cs) and binding:

    public bool IsGamePlaying
    {
        get
        {
            return isGamePlaying;
        }
        set
        {
            isGamePlaying = value;
        }
    }
    private bool isGamePlaying;

<my:SpecialMenuItem ... Visible="{Binding Path=IsGamePlaying, Source={x:Static Application.Current}}" />

When I'm in debug, it reads the IsGamePlaying property, but doesn't make attempt to set the Visible property

How make it work?

Upvotes: 0

Views: 146

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178770

You cannot include any logic in your dependency property wrapper. WPF will, where possible, directly call GetValue/SetValue rather than use your CLR property. You should include any extraneous logic by using metadata in your dependency property. For example:

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
}

The CLR wrapper is merely a convenience for consumers of your class.

Upvotes: 1

Related Questions