1

我正在使用 WPF 用户控件并有以下问题:为什么在将属性设置为 a 之后属性初始化/赋值的行为会发生变化DependencyProperty

让我简要说明一下:

考虑这个UserControl类的代码:

public partial class myUserControl : UserControl
{
    private string _blabla;
    public myUserControl()
    {
        InitializeComponent();
        _blabla = "init";
    }

    //public static DependencyProperty BlaBlaProperty = DependencyProperty.Register(
    //    "BlaBla", typeof(string), typeof(UserControlToolTip));

    public string BlaBla
    {
        get { return _blabla; }
        set { _blabla = value; }
    }
}

这就是UserControl在 XAML 文件中初始化的方式:

<loc:myUserControl BlaBla="ddd" x:Name="myUsrCtrlName" />

我遇到的问题是行set { _blabla = value; }仅在注释掉DependencyProperty声明时调用(根据此示例)。但是,当DependencyProperty行成为程序的一部分时,set { _blabla = value; }行不再被系统调用。

有人可以向我解释这种奇怪的行为吗?

太感谢了!

4

1 回答 1

1

依赖属性的 CLR 包装器(getter 和 setter)只能用于调用依赖属性的GetValueSetValue方法。

例如

public string BlaBla
{
    get { return (string)GetValue(BlaBlaProperty) }
    set { SetValue(BlaBlaPropert, value); }
}

仅此而已...
原因是 WPF 绑定引擎在从 XAML 完成绑定时直接GetValue调用和(例如,不调用 CLR 包装器)。 SetValue

因此,您没有看到它们被调用的原因是因为它们确实没有被调用,而这正是您不应该向 CLR Get 和 Set 方法添加任何逻辑的原因。

编辑
基于 OPs 评论 - 这是一个在DependencyProperty更改时创建回调方法的示例:

public static DependencyProperty BlaBlaProperty = 
       DependencyProperty.Register("BlaBla", typeof(string), Typeof(UserControlToolTip), 
       new FrameworkPropertyMetadata(null, OnBlachshmaPropertyChanged));


private static void OnBlachshmaPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
        UserControlToolTip owner = d as UserControlToolTip;

        if (owner != null)
        {
            // Place logic here
        }
 }
于 2013-01-06T08:50:14.800 回答