WPF Attached Property Data Binding

江枫思渺然 提交于 2019-11-26 09:07:18

问题


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:

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

回答1:


Believe it or not, just add Path= and use parenthesis when binding to an attached property:

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".




回答2:


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.




回答3:


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.

I put the property in brackets and binding worked.

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


来源:https://stackoverflow.com/questions/5832208/wpf-attached-property-data-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!