【问题标题】:Strange behavior for WPF attached property and bindingWPF 附加属性和绑定的奇怪行为
【发布时间】:2013-08-30 09:30:12
【问题描述】:

我正在尝试在网格控件上注册 WPF 附加属性,但是,我今天遇到了非常奇怪的行为:

public static class MyClass
{
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(string),
        typeof(MyClass), null);

    public static string GetMyProperty(DependencyObject d)
    {
        return (string)d.GetValue(MyPropertyProperty);
    }

    public static void SetMyProperty(DependencyObject d, string value)
    {
        d.SetValue(MyPropertyProperty, value); //<-- set breakpoint here
    }
}

XAML:

<GridControl local:MyClass.MyProperty="My Name">
...
</GridControl>

当我这样写时,附加属性的设置器永远不会被执行。和价值永远不会被设定。但我可以窥探网格并发现附加属性附加了一个空值。

但是当我将附加的属性名称更改为:

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("xxxMyProperty", typeof(string),
        typeof(MyClass), null);

即使用除 MyProperty 以外的其他名称。然后可以打断点!和值可以设置!

此外,当我将附加属性更改为:

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(string),
        typeof(UIElement), null);

即把所有者类型改成UIElement,那么我也可以打断点了,不知道为什么?

但是,当我在 XAML 中设置绑定而不是字符串常量时,上述每种情况都会出现异常,提示 A 'Binding' can only be set on a DependencyProperty of a DependencyObject

绑定 XAML 示例:

<GridControl local:MyClass.MyProperty="{Binding MyStringValue}">
...
</GridControl>

以前有人遇到过这种奇怪的行为吗?我在我的情况下缺少什么?提前感谢您的回复!

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    如果您将SetMyProperty 方法称为“setter”,那么您应该知道这些方法只是供您使用的“helper”方法。框架一般不使用这些方法。

    但是,如果您说您想知道值何时发生变化,那么还有另一种方法可以做到这一点。在属性声明中添加PropertyChangedCallback 处理程序:

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(string), typeof(MyClass), 
        new UIPropertyMetadata(default(string.Empty), OnMyPropertyChanged));
    
    public static void OnMyPropertyChanged(DependencyObject dependencyObject, 
        DependencyPropertyChangedEventArgs e)
    {
        string myPropertyValue = e.NewValue as string;
    }
    

    【讨论】:

    • 感谢 Sheridan 的回答,这正是我所需要的!很抱歉回复晚了。
    猜你喜欢
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2012-12-25
    相关资源
    最近更新 更多