RelayCommand canexecute永远不会被重新评估

本文关键字:新评估 评估 canexecute 永远 RelayCommand | 更新日期: 2023-09-27 18:28:56

我有一个应用程序,它在MVVM体系结构中使用RelayCommand

似乎在某个时间点上,CanExecute方法不再得到适当的重新评估。(可能是安装VS2013的最新更新导致了这种情况?)。

下面的代码看起来很基本,我真的希望有人能帮我。

继电器指令声明:

public RelayCommand BrowseTorrentSiteCommand { get; private set; }

继电器指令实例化:

BrowseTorrentSiteCommand = new RelayCommand(BrowseTorrentSiteOnExecuted, BrowseTorrentSiteOnCanExecute); 

CanExecute:的实现

private bool BrowseTorrentSiteOnCanExecute()
{
    return _mainViewViewModel.SelectedTvShow != null;
}

SelectedTvShow属性在VM:中的实现

public TvShowViewModel SelectedTvShow
{
    get { return _selectedTvShow; }
    set
    {
        _selectedTvShow = value; 
        OnPropertyChanged();
    }
}

更新所选电视节目:

    public void TvShowsSelectionChanged()
    {
        Episodes.Clear();
        var queryEpsidesForSelection = new QueryEpsidesForSelection(TvShows);
        foreach (var episode in queryEpsidesForSelection.QueryEpisodes())
        {
            Episodes.Add(episode);
        }
        SelectedTvShow = queryEpsidesForSelection.SelectedTvShow;
        MainCommandsViewModel.DownloadNewestEpisodesCommand.RaiseCanExecuteChanged();
        //MainCommandsViewModel.BrowseTorrentSiteCommand.RaiseCanExecuteChanged();
    }

我有意评论了最后一行强制调用RaiseCanExecuteChanged的内容,我以前从未使用过。显然,这解决了问题,但我使用了很多RelayCommands,它们似乎都遇到了同样的问题:它们的CanExecute方法不再自动重新评估。

CanExecute方法不再被激发的原因是什么?

RelayCommand canexecute永远不会被重新评估

更新

在MvvmLight中有两种RelayCommand的实现方式。

  • using GalaSoft.MvvmLight.Command;中的一个
  • using GalaSoft.MvvmLight.CommandWpf;中的一个

我将名称空间更改为using GalaSoft.MvvmLight.CommandWpf;,一切如常。。。

在对RelayCommand实现的评论中,以下评论给出了它:

// Remarks:
//     If you are using this class in WPF4.5 or above, you need to use the GalaSoft.MvvmLight.CommandWpf
//     namespace (instead of GalaSoft.MvvmLight.Command).  This will enable (or
//     restore) the CommandManager class which handles automatic enabling/disabling
//     of controls based on the CanExecute delegate.

不管怎样,问题解决了。。。(花了我足够长的时间…)

原始答案

@金刚,

也许我误解了你的评论,但这在我刚刚创建的一个示例应用程序中运行良好,以检查我的理智。

    public MainViewModel()
    {
        Command1 = new RelayCommand(OnCommand1Executed, () => true);
        Command2 = new RelayCommand(OnCommand2Executed, OnCommand2CanExecute);
    }
    private void OnCommand1Executed()
    {
        _command2CanExecute = true;
    }
    private void OnCommand2Executed()
    {
        // Not implemented
    }
    private bool OnCommand2CanExecute()
    {
        return _command2CanExecute;
    }

当执行按钮1时,位于其顶部的UI将启用按钮2。

尽管如此,这个基本行为似乎在我的另一个应用程序中不起作用。。。

如有任何帮助,我们将不胜感激。