Reputation: 908
I'm trying to use attached properties to add some presentation logic to my data objects. I'm about to switch to wrappers, but I'm curious why following doesn't work for me. Presentation logic class code is:
public static readonly DependencyProperty TestPropProperty = DependencyProperty.RegisterAttached(
"TestProp",
typeof(string),
typeof(DataClassPresenter),
new PropertyMetadata("[Test]")
);
public static string GetTestProp(DataClass el)
{
return "Haha"; // (string)el.GetValue(TestPropProperty);
}
public static void SetTestProp(DataClass el, string val)
{
el.SetValue(TestPropProperty, val);
}
My XAML for binding to the property value is:
<TextBlock Text="{Binding Path=(prz:DataClassPresenter.TestProp), StringFormat='Depend:\{0\}'}"/>
It works, but always displays "[Test]", "Haha" is never returned and that GetTestProp is never entered. What am I doing wrong?
Upvotes: 2
Views: 689
Reputation: 41393
That's because your get method is not guaranteed to be called. Silverlight (and WPF) can get or set the property value using the DependencyProperty
alone. You should never introduce any logic in the get or set methods.
Also, you should not be using DataClass
as the parameter. The object passed will be the element you are setting the attached property on, which in your example is a TextBlock. So you should have the above accept a DependencyObject
or UIElement
instead of a DataClass
.
Upvotes: 3