2011-04-29 98 views
52

我尝试使用绑定与附加属性。但不能得到它的工作。WPF附加属性数据绑定

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代码:

<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> 

并且绑定错误:

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') 

回答

137

信不信由你,只是添加Path=并用括号绑定到一个附加属性时:

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

此外,您拨打RegisterAttached的电话应以“测试”作为属性名称,而不是“TestProperty”。

+0

我已经试过这个,并得到一个例外:Der Eigenschaftspfad istungültig。 “附件”besitzt keineöffentlicheEigenschaft mit dem Namen \“Test \”。 - > Engl:属性无效。 “附加”不拥有公共属性“测试” – SACO 2011-04-29 13:07:16

+9

“RegisterAttached”调用应通过“Test”,而不是“TestProperty”作为属性名称。 – 2011-04-29 15:22:09

+0

...对...好的,谢谢。现在一切正常。 – SACO 2011-05-02 08:36:36

15

我宁愿发表这个评论肯特的答案,但因为我没有足够的代表这样做...只是想指出,从WPF 4.5,加入Path=是没有必要的了。但是附加的属性名称仍然需要用圆括号包装。

+0

即将发布此评论我自己,没有意识到,这是一个WPF 4.5和功能...很高兴知道,谢谢! – 2013-12-03 21:16:37

+0

不知道为什么,但WPF崩溃,如果我不添加Path =并且正在运行WPF 4.5 我正在运行Win 8.1 – Mo0gles 2014-01-16 10:29:49

+0

即使使用.NET 4.5或.NET 4.6,我也无法让它在没有' Path ='绑定到DataTriggers中的附加属性时。 – 2016-03-03 14:20:16