我尝试使用带有附加属性的绑定。但是不能让它工作。
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')
发布于 2011-04-29 20:48:31
信不信由你,只需添加Path=
并在绑定到附加属性时使用括号:
IsChecked="{Binding Path=(local:Attached.Test), Mode=TwoWay, RelativeSource={RelativeSource Self}}"
此外,您对RegisterAttached
的调用应该传入"Test“作为属性名,而不是"TestProperty”。
发布于 2013-04-12 23:35:10
我更愿意把这篇文章作为对Kent的回答的评论,但因为我没有足够的代表来这么做……我只想指出,从WPF4.5开始,不再需要添加Path=
。但是,附加的属性名称仍然需要用括号括起来。
发布于 2019-01-10 13:50:54
放置一个括号是可行的。我必须在datatemplate
中进行父contentcontrol
到textblock
的自动id绑定。自动化Id是附加属性。
我把属性放在括号里,绑定就起作用了。
AutomationProperties.AutomationId="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContentControl},Path=(AutomationProperties.AutomationId)}"
https://stackoverflow.com/questions/5832208
复制相似问题