воскресенье, 14 февраля 2010 г.

Binding to custom attached property

This is a quick post on an interesting binding issue I came across the other day.

In most cases it is possible to omit the name of the Path parameter in the binding markup. But if you binding to a custom attached property, you may encounter a problem. See the code snippet below:

<Window
x:Class="BindingIssueDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingIssueDemo"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<TextBlock DockPanel.Dock="Top"
Text="{Binding (DockPanel.Dock), RelativeSource={RelativeSource Self}}" />
<TextBlock local:CustomProperties.Description="Custom attached property"
Text="{Binding (local:CustomProperties.Description), RelativeSource={RelativeSource Self}}" />
</DockPanel>
</Window>

When you run the program, only the first TextBlock has text, the second one remains empty. And debugger output window prints the following error message:
System.Windows.Data Error: 39 : BindingExpression path error: '(local:CustomProperties.Description)' property not found on 'object' ''TextBlock' (Name='')'. BindingExpression:Path=(local:CustomProperties.Description); DataItem='TextBlock' (Name=''); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
I Googled a bit and found that the problem occurs when binding to attached properties in a non-default XML namespace. To workaround the issue you have to explicitly specify Path= in binding markup:
 
<TextBlock local:CustomProperties.Description="Custom attached property"
Text="{Binding Path=(local:CustomProperties.Description), RelativeSource={RelativeSource Self}}" />
 
Seems like this issue has been fixed in Visual Studio 2010 RC / .NET 4.0.

Комментариев нет:

Отправить комментарий

Random thoughts, ideas and questions on .NET development

Постоянные читатели