Another quick post. In an effort to blog more I am trying to blog quick snippets I come across instead of full blown manifestos.
Colleagues of mine at InterKnowlogy came across an interesting binding edge case the other day and I thought it would make a decent post. In the past I have needed to bind to attached properties (although it has been rare). Typically I was doing something like this :
<DockPanel Height="100" Width="100">
<TextBlock DockPanel.Dock="Left"
Text="{Binding RelativeSource={RelativeSource Self}, Path=(DockPanel.Dock)}" />
<TextBlock DockPanel.Dock="Right"
Text="{Binding RelativeSource={RelativeSource Self}, Path=(DockPanel.Dock)}" />
<TextBlock DockPanel.Dock="Top"
Text="{Binding RelativeSource={RelativeSource Self}, Path=(DockPanel.Dock)}" />
<TextBlock DockPanel.Dock="Bottom"
Text="{Binding RelativeSource={RelativeSource Self}, Path=(DockPanel.Dock)}" />
</DockPanel>
Where I am binding to the attached property “DockPanel.Dock.” The basic trick here is to add the parentheses around the path to indicate you are binding to an attached property.
The edge case we came across this past week was binding to a custom attached property. Something like this
<TextBlock Custom:MyAttachedProperty.CustomString="Some String"
Text="{Binding RelativeSource={RelativeSource Self}, Path=(MyAttachedProperty.CustomString)}" />
Where I am binding to “MyAttachedProperty.CustomString.” This however doesn’t work as posted. It will throw and error stating it cannot find type MyAttachedProperty. The solution may be obvious to most but we were stuck on it for a few minutes.
You have to add the namespace prefix to the property in the binding in order for the Binding markup extension to be able to resolve the custom type and find the attached property.
So the example above is corrected like this:
<TextBlock Custom:MyAttachedProperty.CustomString="Some String"
Text="{Binding RelativeSource={RelativeSource Self}, Path=(Custom:MyAttachedProperty.CustomString)}" />
Like I said, might be obvious to most but it isn’t something I had done before so it took a few minutes to discover the correct way to do it.