绑定后如何捕获属性更改事件

时间:2012-10-09 11:19:07

标签: wpf events data-binding

我有自定义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已更改的事件?

2 个答案:

答案 0 :(得分:3)

这样的事情(这会捕捉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的“客户”想要针对特定​​实例捕获对​​该属性的更改,那么他们可以使用:

CustomCtrl instanceofsomecustomctrl = .......

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

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

答案 1 :(得分:1)

我认为这就是你要找的东西,你想要一个onChangeHandler事件。

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

public string Prova
{
    get { return (string)GetValue(ProvaProperty); }
    set 
    {
        SetValue(ProvaProperty, value); 
        OnPropertyChanged("Prova");
    }
}
protected void OnPropertyChanged(string prova)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(prova));
        }
    }
 //This portion could go in the class where the event takes place
 private delegate void UpdateDelegate(DependencyProperty dp, Object value);


}