WPF Attached Property Data Binding

WpfXamlBindingAttached Properties

Wpf Problem Overview


I try to use binding with an attached property. But can't get it working.

public class Attached
{
    public static DependencyProperty TestProperty =
        DependencyProperty.RegisterAttached("TestProperty", typeof(bool), typeof(Attached),
        new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Inherits));

    public static bool GetTest(DependencyObject obj)
    {
        return (bool)obj.GetValue(TestProperty);
    }

    public static void SetTest(DependencyObject obj, bool value)
    {
        obj.SetValue(TestProperty, value);
    }
}

The XAML Code:

<Window ...>
    <StackPanel local:Attached.Test="true" x:Name="f">
        <CheckBox local:Attached.Test="true" IsChecked="{Binding (local:Attached.Test), Mode=TwoWay, RelativeSource={RelativeSource Self}}" />
        <CheckBox local:Attached.Test="true" IsChecked="{Binding (local:Attached.Test), Mode=TwoWay}" />
    </StackPanel>
</Window>

And the Binding Error:

System.Windows.Data Error: 40 : BindingExpression path error: '(local:Attached.Test)' property not found on 'object' ''StackPanel' (Name='f')'. BindingExpression:Path=(local:Attached.Test); DataItem='StackPanel' (Name='f'); target element is 'CheckBox' (Name=''); target property is 'IsChecked' (type 'Nullable`1')

Wpf Solutions


Solution 1 - Wpf

Believe it or not, just add Path= and use parenthesis when binding to an attached property:

IsChecked="{Binding Path=(local:Attached.Test), Mode=TwoWay, RelativeSource={RelativeSource Self}}"

In addition, your call to RegisterAttached should pass in "Test" as the property name, not "TestProperty".

Solution 2 - Wpf

I'd have preferred to post this as a comment on Kent's answer but since I don't have enough rep to do so... just wanted to point out that as of WPF 4.5, adding Path= isn't necessary anymore. However the attached property name still needs to be wrapped with parentheses.

Solution 3 - Wpf

Putting a bracket works. I had to do automation id binding of a parent contentcontrol to a textblock in datatemplate. Automation Id is an attached property.

I put the property in brackets and binding worked.

AutomationProperties.AutomationId="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContentControl},Path=(AutomationProperties.AutomationId)}" 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel BişarView Question on Stackoverflow
Solution 1 - WpfKent BoogaartView Answer on Stackoverflow
Solution 2 - WpfLivvenView Answer on Stackoverflow
Solution 3 - WpfPradnya NaikView Answer on Stackoverflow