How to catch a property that changed an event after binding

I have a custom 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)); } 

I am doing this simple binding:

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

Now c.Prova has a " new string ", but how can I catch an event in my CustomControl class, telling me that Prova has changed?

+4
source share
2 answers

Something like this (this will catch the changes in 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. } 

If the "clients" of your CustomCtrl wanted to catch a change in this property for a specific instance, then they can use:

 CustomCtrl instanceofsomecustomctrl = ....... DependencyPropertyDescriptor descr = DependencyPropertyDescriptor.FromProperty(CustomCtrl.ProvaProperty, typeof(CustomCtrl)); if (descr != null) { descr.AddValueChanged(instanceofsomecustomctrl, delegate { // do something because property changed... }); } 
+3
source

I think this is what you are looking for, you need the onChangeHandler event.

 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); } 
+1
source

Source: https://habr.com/ru/post/1438631/


All Articles