WPF Usercontrol属性初始化
我正在玩弄WPF Usercontrols,并有以下问题:为什么属性被设置为WPF Usercontrol属性初始化,wpf,user-controls,dependency-properties,Wpf,User Controls,Dependency Properties,我正在玩弄WPF Usercontrols,并有以下问题:为什么属性被设置为DependencyProperty后,属性初始化/赋值的行为会发生变化 让我简单地说明一下: 对于UserControl类,请考虑以下代码: public partial class myUserControl : UserControl { private string _blabla; public myUserControl() { InitializeComponent(
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" />
我遇到的问题是,只有在注释掉DependencyProperty声明时才调用行集{{u blabla=value;}(如本例所示)。但是,当DependencyProperty行成为程序的一部分时,系统将不再调用set{{blabla=value;}行
能给我解释一下这种奇怪的行为吗
万分感谢 依赖项属性的CLR包装器(getter和setter)只能用于调用依赖项属性的GetValue
和SetValue
方法
e、 g
没有别的了……原因是当从XAML进行绑定时,WPF绑定引擎直接调用
GetValue
和SetValue
(例如,不调用CLR包装器)
因此,您没有看到它们被调用的原因是因为它们确实没有被调用,而这正是您不应该向CLR Get和Set方法添加任何逻辑的原因
编辑基于OPs注释-以下是当
dependencProperty
更改时创建回调方法的示例:
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
}
}
依赖项属性的CLR包装器(getter和setter)只能用于调用依赖项属性的GetValue
和SetValue
方法
e、 g
没有别的了……原因是当从XAML进行绑定时,WPF绑定引擎直接调用
GetValue
和SetValue
(例如,不调用CLR包装器)
因此,您没有看到它们被调用的原因是因为它们确实没有被调用,而这正是您不应该向CLR Get和Set方法添加任何逻辑的原因
编辑基于OPs注释-以下是当
dependencProperty
更改时创建回调方法的示例:
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的新值的调用,以便根据该值在控件内执行某些操作。更改dependency属性时,您可以创建回调方法。示例添加到我的答案中,非常感谢@Blachshma-这是非常好的帮助和建议!我现在让UserControl框架开始工作了!您好@Blachshma,非常感谢,但在这种情况下,如何拦截依赖属性的GetValue/SetValue调用,以及在哪里为值的更改添加自己的逻辑?我当前在上述的get/set位置截获对UserControl的新值的调用,以便根据该值在控件内执行某些操作。更改dependency属性时,您可以创建回调方法。示例添加到我的答案中,非常感谢@Blachshma-这是非常好的帮助和建议!我现在让UserControl框架开始工作了!