简体   繁体   中英

How do I have a method in code-behind called when a property is updated?

What I need is to be able to execute code in a code-behind for my view class when a property on my view-model is updated. My understanding is that I need to use a dependency-property.

My view-model does implement 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 view:

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));

Here is where I set up my 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 break-point on the setter for the property in my view, it never gets hit even after I watch the value change in the view-model, and the PropertyChanged event raised. Ultimately, my goal is to be able to put more code in the setter.

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

More often than not, these problems are simple little obvious things that I've missed. Nothing I'm trying is helping me sort this one out, though.

When I put a break-point on the setter for the property in my view, it never gets hit even after I watch the value change in the view-model, and the PropertyChanged event raised. Ultimately, my goal is to be able to put more code in the setter.

You can't do this. When you're using DependencyProperties, the setter is never called when the bound property changes. It's only purpose is to allow you to set the DP from code.

You need to, instead, add a PropertyChangedCallback to the metadata on your DP, and add the extra code there. This will get called when the DP value updates, whether via binding, code, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM