WPF-related property data binding

I am trying to use a binding with an attached property. But he cannot make it work.

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); } } 

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') 
+54
wpf binding xaml attached-properties
Apr 29 '11 at 12:45
source share
3 answers

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

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

In addition, your RegisterAttached call should pass to โ€œTestโ€ as the name of the property, not โ€œTestPropertyโ€.

+145
Apr 29 '11 at 12:48
source share

I would rather post this as a comment on Kent's answer, but since I don't have enough repetitions, I just want to point out that with WPF 4.5, adding Path= not necessary anymore. However, the name of the attached property should still be enclosed in parentheses.

+17
Apr 12 '13 at 15:35
source share

Bracket installation works. I had to make the automation identifier of binding the parent contentcontrol to the textblock in the datatemplate . Automation ID is a nested property.

I set the property in brackets and the binding worked.

 AutomationProperties.AutomationId="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContentControl},Path=(AutomationProperties.AutomationId)}" 
-one
Jan 10 '19 at 5:50
source share



All Articles