4

我有一个习惯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发生变化的事件?

4

2 回答 2

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...
        });
} 
于 2012-10-09T11:30:28.363 回答
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);


}
于 2012-10-09T11:30:42.057 回答