WPF 附加属性数据绑定(bind)

标签 wpf xaml binding attached-properties

我尝试使用带有附加属性的绑定(bind)。但无法让它工作。

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>

以及绑定(bind)错误:

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

最佳答案

不管你信不信,只需添加 Path= 并在绑定(bind)到附加属性时使用括号即可:

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

此外,对 RegisterAttached 的调用应传入“Test”作为属性名称,而不是“TestProperty”。

关于WPF 附加属性数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5832208/

相关文章:

c# - 使用 CommandParameter 在 TreeView 项上进行键绑定(bind)

wpf - 将 RichTextBox 绑定(bind)到字符串

c# - 与 MahAppsMetro ProgressIndicator 绑定(bind)失败

ruby - Procs的绑定(bind)

wpf - 强制 WPF 在 ItemsControl 中创建项目

wpf - 如何在单击项目时展开 WPF TreeView

c# - 在 Caliburn.Micro 中如何将操作绑定(bind)到嵌套的 ViewModel 方法?

WPF控件模板

c# - TextBlock 上的删除线效果

c# - 将文本框绑定(bind)到字典