即使有正确的指令,也不能识别RaiseCanExecuteChanged

本文关键字:也不能 识别 RaiseCanExecuteChanged 指令 | 更新日期: 2023-09-27 17:51:02

我仍然在学习mvvmc#编码,但我遇到了一个问题,我不知道如何解决它。我的项目似乎无法识别

RaiseCanExecuteChanged 

即使我使用

System.Windows.Input;

我用MVVM LightNET4.5

我一直得到的错误是

`System.Windows.Input.ICommand` does not contain a definition for '`RaiseCanExecuteChanged`' and no extension method '`RaiseCanExecuteChanged`' accepting a first argument of type 'System.Windows.Input.Icommand' could be found(are you missing a using directive or an assembly reference?)

以前有人遇到过这个问题吗?谢谢你的帮助

下面是我在视图模型中用来创建命令 的代码
public class NetworkingViewModel : ViewModelBase, INotifyPropertyChanged
{
 public NetworkingViewModel()
    {
       AddPersonCommand = new RelayCommand(AddPerson,CanAddName );
    }
 public ICommand AddPersonCommand {get; private set;}
 private void AddPerson()
    {
        *adds person to an observableCollection*
    }
 private bool CanAddName()
    {
        return !string.IsNullOrEmpty(Group);   
    }
 public string Group   // the Name property
    {
        get { return _group; }
        set 
        { 
            if(value !=_group)
            {
                _group = value;
                RaisePropertyChanged("Group");
                AddPersonCommand.RaiseCanExecuteChanged();
            }
        }
    }
}

即使有正确的指令,也不能识别RaiseCanExecuteChanged

ICommand没有RaiseCanExecuteChanged,但是RelayCommand(您正在使用)做…所以你可以试着用cast或其他方法:

var myCommand = AddPersonCommand as RelayCommand;
if(myCommand != null) 
  myCommand.RaiseCanExecuteChanged();

将command属性定义为relay command:

public ICommand AddPersonCommand {get;私人设置;}

public RelayCommand AddPersonCommand {get; private set;}

如果你正在使用MVVM Light你可能应该使用RelayCommands而不是iccommands,和MVVM Light的raisecanexecutechange。这是在GalaSoft.MvvmLight.Command命名空间中(或者GalaSoft.MvvmLight.CommandWpf命名空间- http://blog.galasoft.ch/posts/2015/01/re-enabling-the-commandmanager-feature-with-relaycommand-in-mvvm-light-v5)。参考System.Windows.Input .

看:http://www.mvvmlight.net/help/net45/html/404e779f - 7 - c2b - 875 f - bf17 b8ad84bfb7ef.htm

正如@Bijington在评论中所说,RaiseCanExecuteChanged在ICommand中不存在。ICommand有CanExecute方法,它应该工作。或者你可以在Group属性setter中将AddPersonCommand转换为RelayCommand,或者从一开始就使用RelayCommand作为AddPersonCommand属性的类型。