How can I call a method when calling the code when updating the property?

I need to be able to execute code in code for my view class when a property on my view model is updated. I understand that I need to use the dependency property.

My view model implements INotifyPropertyChanged .

Here is the property in my view model:

 private DisplayPosition statusPosition; public DisplayPosition StatusPosition { get { return this.statusPosition; } set { this.statusPosition = value; this.OnPropertyChanged("StatusPosition"); } } 

Here is my dependency property in my opinion:

 public DisplayPosition StatusPosition { get { return (DisplayPosition)GetValue(StatusPositionProperty); } set { SetValue(StatusPositionProperty, value); } } public static readonly DependencyProperty StatusPositionProperty = DependencyProperty.Register( "StatusPosition", typeof(DisplayPosition), typeof(TranscriptView), new PropertyMetadata(DisplayPosition.BottomLeft)); 

This is where I set the binding in my view class (handler for this.DataContextChanged ):

 private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { Binding myBinding = new Binding("StatusPosition"); myBinding.Source = this.DataContext; myBinding.NotifyOnTargetUpdated = true; this.SetBinding(TranscriptView.StatusPositionProperty, myBinding); } 

When I put a breakpoint in the setter for a property in my view, it never hits even after I observe a change in value in the view model and the PropertyChanged event. Ultimately, my goal is to be able to add more code to the setter.

The hairy detail, if you're curious, is that I need to move a TextBlock between multiple StackPanels based on this value. I can't seem to find a way for XAML only.

Most often, these problems are simple, little obvious things that I missed. Nothing I'm trying to help me figure this out.

+4
source share
1 answer

When I put a breakpoint in the customizer for a property in my view, it never hits even after I observe a change in value in the view model and the PropertyChanged event. Ultimately, my goal is to be able to add more code to the setter.

You cannot do this. When you use DependencyProperties, the setter is never called when the binding property changes. The sole purpose is to allow you to install DP from code.

Instead, you need to add PropertyChangedCallback to the metadata of your DP and add additional code there. This will be called when updating the DP value, whether through binding, code, etc.

+2
source

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


All Articles