Sloth Armstrong
Sloth Armstrong

Reputation: 1066

How to bind IsEnabled property to a more dynamic property in ViewModel?

I have a TabItem that has its IsEnabled property bound to a ViewModel property called IsSaved.

It looks like this:

<TabItem Header="POs"
         IsEnabled="{Binding IsSaved, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">

Beautiful, right? In my ViewModel the property IsSaved is not quite as simple. It is defined as:

public bool IsSaved
{
    get
    {
        return IsDeveloper 
                   && CheckValidation(null) 
                   && !IsDirty 
                   && !displayMasterRepository.IsObjectChanged(); //TODO: this does not work.
    }
}

Now obviously this will never update the View because there is on OnPropertyChanged event happening here. In fact, if I knew where to put the OnPropertyChanged I would, but in this instance many, many things can trigger a change of this property so that doesn't make sense. What would someone do in this situation?

If this was a button with a command binding, for example, I would pass IsSaved into the delegate command as a CanExecute parameter and it would work dynamically. Is there something like that for a situation like this? Thanks!

Upvotes: 2

Views: 389

Answers (1)

eran otzap
eran otzap

Reputation: 12533

You can call OnPropertyChanged from any where in your code in the scope of your class.

     OnPropertyChanged("IsSaved"); 

Additionally i like to expose a public function for other classes to raise my property change , Something like :

     public void RefreshIsSaved()
     {
        OnPropertyChanged("IsSaved");  
     }

Or something a little less specific like :

     public void RaisePropertyChanged(string propertyName)
     {
        OnPropertyChanged(propertyName);     
     }

Is this what your asking ?

As a side note you can also write the property in a clearer manner:

      public bool IsSaved
      {
          get
           {
                if(IsDirty || displayMasterRepository.IsObjectChanged())
                     return false;

                return IsDeveloper && CheckValidation(null);
            }
      }

This will be much easier to maintain if more complex conditions would be added to your property , and it's much more readable .

Upvotes: 4

Related Questions