简体   繁体   中英

WP7: Binding to attached properties

I'm trying to bind a data value to an attached property. However, it just dont get it to work.

I defined it like:

public static class MyClass
{
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(string),
        typeof(MyClass), new PropertyMetadata(null));

    public static string GetMyProperty(DependencyObject d)
    {
        return (string)d.GetValue(MyPropertyProperty);
    }

    public static void SetMyProperty(DependencyObject d, string value)
    {
        d.SetValue(MyPropertyProperty, value);
    }
}

Now the XAML I use it looks something like this:

<TextBlock local:MyClass.MyProperty="{Binding MyStringValue}" />

I set a breakpoint in the SetMyProperty method, but it is never called. It does not raise any error, it is just never set or asked for. However, if I change the value in XAML to a fixed string, it gets called:

<TextBlock local:MyClass.MyProperty="foobar" />

What am I missing?

Note: the above example is the minimal version that shows the same strange behavior. My actual implementation makes more sense than this of course.

Thanks in advance for any hint!

And the binding wont trigger your SetMyProperty ever - if you need controll over when the value changes you must use the override of PropertyMetadata that expects a "Change"-Handler



... new PropertyMetadata(
    null,
    new PropertyChangedCallback((sender, e) => {
      var myThis = (MyClass)sender;
      var changedString = (string)e.NewValue;
      // To whatever you like with myThis ( = the sender object) and changedString (= new value)
    })

Change the type of the second argument in SetMyProperty to type Object.

You are going to get a Binding object, not a String, as the value there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM