Know is a view model property is being set from source or target

Know is a view model property is being set from source or target

Problem Description:

Maybe this is a stupid question, but is there a way to know if a property on the view model is being set from the source (view model) or the target (view)?

I have a weird scenario in which I have a property in the view model which is bound to a dependency property of a UserControl that I have placed in one of my views. Dependency property is registered as TwoWay. I would like to know when the view model property is being set from the view (as a result of an update in the dependency property in the UserControl side) or is being set from the view model.

Of course I could do a kind of a hack job and use a boolean variable in the view model, I mean, set it to true when I am setting it from the view model and then check this variable in the setter of the view model property and finally if true, return it to false at the end of the setter.

Solution – 1

is there a way to know if a property on the view model is being set from the source (view model) or the target (view)?

No, but you don’t have to.

Of course I could do a kind of a hack job and use a boolean variable in the view model

Don’t do that.

Do this instead:

class ViewModel //PropertyChanged implementation ommited for simplicity
{
   public string MyProperty {get; set;}

   public string MyPropertyForBinding 
   {
      get => MyProperty;
      set 
     {
        MyProperty = value;
        //your additional logic when setting from binding
     }
   }
}

or this

private string _myProperty;

public string MyProperty
{
    get { return _myProperty; }
    set 
    { 
       SetProperty(ref _myProperty, value);
       //your additional logic when binding updates source
    }
}

public void SetMyPropertyFromElsewhere(string value)
{
    SetProperty(ref _myProperty, value, nameof(MyProperty));
    //your additional logic when setting from elsewhere
}
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject