从另一个ViewModel的操作更新CanExecute

时间:2015-04-29 08:41:18

标签: c# mvvm canexecute

我在哪里运行CreateBestPriceListCanExecute方法,以便在下面的代码段中更新我的CanExecute

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

我的CreateBestPrice方法正在使用数据库,它有一个在后台运行的自动数据库更新程序,有时会上传信息。我需要我的CanExecute在那个时候是假的,还有另一种方法吗?

1 个答案:

答案 0 :(得分:1)

只需使用CanExecute方法更新CreateBestPriceListCanExecute媒体资源:

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

然后,您可以根据频率调用CreateBestPriceListCanExecute方法。例如,您可以从DispatcherTimer.Tick事件处理程序中调用它。