Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF mvvm property in viewmodel without setter?

Tags:

c#

mvvm

wpf

I'm dealing with some WPF problems using and sticking to the MVVM pattern.

Most of my properties look like this:

public string Period
{
    get { return _primaryModel.Period; }
    set
    {
        if (_primaryModel.Period != value)
        {
            _primaryModel.Period = value;
            RaisePropertyChanged("Period");
        }
    }
}

This works excellent.

However I also have some properties like this:

public bool EnableConsignor
{
    get
    {
        return (ConsignorViewModel.Id != 0);
    }
}

It doesn't have a setter as the id is changed "automatically" (every time the save of ConsignorViewModel is called. However this leads to the problem that the "system" doesn't know when the bool changes from false to true (as no RaisePropertyChanged is called).

like image 701
mosquito87 Avatar asked Mar 17 '23 12:03

mosquito87


1 Answers

For these kinds of properties, you need to just raise PropertyChanged when the dependent data is changed. Something like:

public object ConsignorViewModel
{
   get { return consignorViewModel; }
   set
   {
       consignorViewModel = value;
       RaisePropertyChanged("ConsignorViewModel");
       RaisePropertyChanged("EnableConsignor");
   } 
}

RaisePropertyChanged can be invoked in any method, so just put it after whatever operation that would change the return value of EnableConsignor is performed. The above was just an example.

like image 187
BradleyDotNET Avatar answered Mar 19 '23 10:03

BradleyDotNET