Dan*_*şar 63 wpf xaml binding attached-properties
我尝试使用附加属性绑定.但无法让它发挥作用.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
和绑定错误:
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')
Run Code Online (Sandbox Code Playgroud)
Ken*_*art 157
信不信由你,只需Path=
在绑定到附加属性时添加并使用括号:
IsChecked="{Binding Path=(local:Attached.Test), Mode=TwoWay, RelativeSource={RelativeSource Self}}"
Run Code Online (Sandbox Code Playgroud)
此外,您的调用RegisterAttached
应该将"Test"作为属性名称传递,而不是"TestProperty".
Liv*_*ven 19
我更愿意将此作为对肯特答案的评论发布,但由于我没有足够的代表这样做...只是想指出,从WPF 4.5开始,Path=
不再需要添加.但是,附加的属性名称仍然需要用括号括起来.
归档时间: |
|
查看次数: |
35103 次 |
最近记录: |