WPF附加属性数据绑定

时间:2011-04-29 12:45:31

标签: 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);
    }
}

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

3 个答案:

答案 0 :(得分:149)

信不信由你,只需添加Path=并在绑定到附加属性时使用括号:

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

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

答案 1 :(得分:18)

我更愿意将此作为对Kent答案的评论发布,但由于我没有足够的代表这样做...只是想指出,从WPF 4.5开始,添加Path= isn不再需要了。但是附加的属性名称仍然需要用括号括起来。

答案 2 :(得分:-1)

放入括号即可。我必须将父contentcontroltextblock中的datatemplate进行自动化ID绑定。自动化ID是附加属性。

我将该属性放在方括号中,并且绑定有效。

AutomationProperties.AutomationId="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContentControl},Path=(AutomationProperties.AutomationId)}"