繁体   English   中英

WPF用户控件属性初始化

[英]WPF Usercontrol Property Intitialization

我在玩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; }
    }
}

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

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

我的问题是行 is called ONLY when the declaration is commented out (as per this example). 仅当声明被注释掉时,才调用 (按照此示例)。 line becomes part of the program the 但是,当行成为程序的一部分时, line is no longer called by the system. 行不再被系统调用。

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

太感谢了!

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

例如

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

没什么...
原因是从XAML进行绑定时,WPF绑定引擎直接调用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
        }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM