【问题标题】:WPF Usercontrol Property IntitializationWPF用户控件属性初始化
【发布时间】:2013-01-06 07:42:11
【问题描述】:

我正在玩 WPF 用户控件并有以下问题:为什么在将属性设置为 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; } 行不再被系统调用。

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

谢谢一百万!

【问题讨论】:

    标签: wpf user-controls dependency-properties


    【解决方案1】:

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

    例如

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

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

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

    编辑
    基于 OP 的评论 - 以下是在 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
            }
     }
    

    【讨论】:

    • 嗨@Blachshma,非常感谢您,但在这种情况下,您如何拦截 GetValue/SetValue 调用依赖属性以及在哪里你会为价值观的变化宣传你自己的逻辑吗?我目前按照上述在 get/set 位置拦截对 UserControl 新值的调用,以便根据值在控件内部采取一些行动。
    • 可以在依赖属性改变时创建回调方法。示例已添加到我的答案中
    • 非常感谢@Blachshma - 这是很好的帮助和建议!我的 UserControl 框架现在可以工作了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2014-08-01
    • 1970-01-01
    相关资源
    最近更新 更多