gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:47:46 24 4
gpt4 key购买 nike

我尝试使用带有附加属性的绑定(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com