Search code examples
c#mvvmcanexecute

Update CanExecute from another ViewModel's actions


Where do I run my CreateBestPriceListCanExecute method in order to update my CanExecute in the below code snippet?

class BestPriceViewModel : ViewModelBase
{
    ObservableCollection<BestPriceModel> bestPriceList = new ObservableCollection<BestPriceModel>();

    public ICommand createBestPriceListCommand;
    private bool canExecute = true;
    public BestPriceViewModel()
    {
        createBestPriceListCommand = new RelayCommand(CreateBestPriceList, param => this.CanExecute);
        btnLoadItemList = "Import";
    }     public ObservableCollection<BestPriceModel> BestPriceList
    {
        get { return this.bestPriceList; }
        set
        {
            if (this.bestPriceList != value)
            {
                this.bestPriceList = value;
                this.OnPropertyChanged("BestPriceList");
            }
        }
    }

    public bool CanExecute
    {
        get
        {
            return this.canExecute;
        }

        set
        {
            if (this.canExecute == value)
            {
                return;
            }

            this.canExecute = value;
        }
    }
    public ICommand CreateBestPriceListCommand
    {
        get
        {
            return createBestPriceListCommand;
        }
        set
        {
            createBestPriceListCommand = value;
        }
    }

    public bool CreateBestPriceListCanExecute()
    {
        bool DbCheck = DataBaseAccess.connection.State != ConnectionState.Open &&
        DataBaseAccess.connection.State != ConnectionState.Fetching &&
        DataBaseAccess.connection.State != ConnectionState.Executing ? true : false;
        return DbCheck;
    }
}

My CreateBestPrice method is using the database, and it has an automatic database updater running in the background that uploads information sometimes. I need my CanExecute to be false at those times, is there another way to do it?


Solution

  • Just update your CanExecute property from your CreateBestPriceListCanExecute method:

    public void CreateBestPriceListCanExecute()
    {
        CanExecute = DataBaseAccess.connection.State != ConnectionState.Open &&
        DataBaseAccess.connection.State != ConnectionState.Fetching &&
        DataBaseAccess.connection.State != ConnectionState.Executing ? true : false;
    }
    

    Then it's just up to you as to how often you call your CreateBestPriceListCanExecute method. You could call it from a DispatcherTimer.Tick event handler for example.