绑定后如何捕获属性更改事件 [英] How to catch a property changed event after binding

查看:135
本文介绍了绑定后如何捕获属性更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的 UserControl

public partial class CustomCtrl : UserControl
{
    public CustomCtrl()
    {
        InitializeComponent();
    }

    public string Prova
    {
        get { return (string)GetValue(ProvaProperty); }
        set 
        {
            SetValue(ProvaProperty, value); 
        }
    }

    public static readonly DependencyProperty ProvaProperty =
        DependencyProperty.Register("Prova", typeof(string), typeof(CustomCtrl));

}

我做这个简单的绑定:

CustomCtrl c = new CustomCtrl();
TextBlock t = new TextBlock();
c.SetBinding(CustomCtrl.ProvaProperty, new Binding("Text") { Source = t });
t.Text = "new string";

现在 c.Prova new string ,但是如何在我的 CustomControl 类中捕获事件,通知我 Prova 已更改?

Now c.Prova is "new string", but how can I catch in my CustomControl class the event informing me that Prova has changed?

推荐答案

这样的东西(这将捕获<$ c $的所有实例的更改c> CustomCtrl ):

Something like this (this will catch changes on all instances of CustomCtrl):

public static readonly DependencyProperty ProvaProperty =
    DependencyProperty.Register(
    "Prova",
    typeof(string),
    typeof(CustomCtrl),
    new PropertyMetadata( new PropertyChangedCallback(OnValueChanged) )
);

private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // This is called whenever the Prova property has been changed.
}

如果您的 CustomCtrl 想要获取特定实例的该属性的更改,然后他们可以使用:

If "clients" of your CustomCtrl wanted to catch a change to that property for a specific instance then they could use:

CustomCtrl instanceofsomecustomctrl = .......

DependencyPropertyDescriptor descr = 
                  DependencyPropertyDescriptor.FromProperty(CustomCtrl.ProvaProperty, typeof(CustomCtrl));

if (descr != null)
{
    descr.AddValueChanged(instanceofsomecustomctrl, delegate
        {
            // do something because property changed...
        });
} 

这篇关于绑定后如何捕获属性更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆