WPF 附加属性数据绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5832208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Attached Property Data Binding
提问by Daniel Bi?ar
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:
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>
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')
回答by Kent Boogaart
Believe it or not, just add Path=
and use parenthesis when binding to an attached property:
信不信由你,只需Path=
在绑定到附加属性时添加并使用括号:
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".
此外,您的调用RegisterAttached
应该传入“Test”作为属性名称,而不是“TestProperty”。
回答by Livven
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.
我更愿意将此作为对 Kent 答案的评论发布,但由于我没有足够的代表来这样做……只是想指出,从 WPF 4.5 开始,Path=
不再需要添加。但是附加的属性名称仍然需要用括号括起来。
回答by Pradnya Naik
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.
放置支架有效。我必须将父对象的自动化 id 绑定contentcontrol
到textblock
in datatemplate
。自动化 ID 是附加属性。
I put the property in brackets and binding worked.
我把属性放在括号里,绑定成功了。
AutomationProperties.AutomationId="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContentControl},Path=(AutomationProperties.AutomationId)}"