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 bre开发者_如何学Goakpoint 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.
精彩评论