MKII
MKII

Reputation: 911

Data binding to an attached property

I have tried to use an Attached Property to one of my controls in .NET 3.5. The idea is that the control needs to be focused after a specific operation. I wanted to bind this property to a value on the ViewModel, so that the property could be changed as needed (i.e. when I changed the value on the ViewModel, it would update the value in the Attached Property).

Attached Property

class FocusProperty : DependencyObject
{
    public static DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached ("IsFocused",
                                                                          typeof (bool),
                                                                          typeof (FocusProperty),
                                                                          new UIPropertyMetadata (false, OnIsFocusedChanged));

    public static bool GetIsFocused (DependencyObject DObject)
    {
        return (bool)DObject.GetValue (IsFocusedProperty);
    }

    public static void SetIsFocused (DependencyObject DObject, bool Value)
    {
        DObject.SetValue (IsFocusedProperty, Value);
    }

    public static void OnIsFocusedChanged (DependencyObject DObject, DependencyPropertyChangedEventArgs Args)
    {
        UIElement Control = DObject as UIElement;
        bool NewValue = (bool)Args.NewValue;
        bool OldValue = (bool)Args.OldValue;

        // REMOVE TODO
        System.Windows.MessageBox.Show ("OI");

        if (NewValue && !OldValue && !Control.IsFocused)
        {
        Control.Focus ();
        }
    }
}

In the XAML, this is how it is used:

a:FocusProperty.IsFocused="{Binding Path=IsListFocused}

Where IsListFocused is a bool property on the ViewModel:

public bool IsListFocused
{
    get { return isListFocused_; }
    set
    {
        isListFocused_ = value;
        OnPropertyChanged ("IsFocused");
    }
}

It doesn't work though - when the IsListFocused is changed, the MessageBox doesn't show up as expected.

I have been looking for help on the topic, but it seems like Attached Properties are not something used a lot, and as such there isn't much in the way of support.

My question is: Why is the above snippet not working as expected?

Upvotes: 1

Views: 76

Answers (1)

Clemens
Clemens

Reputation: 128061

In the IsListFocused property setter in your view model, replace

OnPropertyChanged("IsFocused");

by

OnPropertyChanged("IsListFocused");

Upvotes: 2

Related Questions