Relaycommand ICommand.CanExecute未触发

时间:2017-02-24 23:01:13

标签: c# wpf mvvm relaycommand canexecute

我有以下问题:

我有一个带有执行和canexecute方法的relaycommand,但每次调用raisecanexecutechanged();它在relaycommand中调用raisecanexecutechanged,为它设置一个新的委托,然后返回到视图模型。

相同的设置适用于另一个视图模型。我检查了1000次不同但我找不到任何东西。

如果你能帮助我,我真的很感激。

    public RelayCommand UpdateAMSCommand { get; private set; }

    public AMSSettingsViewModel(IEventAggregator eventAggregator)
    {
        UpdateAMSCommand = new RelayCommand(OnUpdateAMS, CanUpdateAms);
        CustomAMSOffices.ListChanged += listChanged;
        CustomAMSContacts.ListChanged += listChanged;
    }

    private void listChanged(object sender, ListChangedEventArgs e)
    {
        if (sender != null)
        {
            if (sender is BindingList<CustomAMSOffice>)
            {
                BindingList<CustomAMSOffice> temp =  (BindingList<CustomAMSOffice>)sender;

                if (temp.Count > _amsOfficesItemsCounter)
                {
                    _amsOfficesItemsCounter = temp.Count;

                    for (int i = 0; i < temp.Count; i++)
                    {
                        temp[i].ErrorsChanged += RaiseCanExecuteChanged;
                    }
                }   
            }
            else if (sender is BindingList<CustomAMSContact>)
            {
                BindingList<CustomAMSContact> temp = (BindingList<CustomAMSContact>)sender;

                if (temp.Count > _amsContactsItemsCounter)
                {
                    _amsContactsItemsCounter = temp.Count;

                    for (int i = 0; i < temp.Count; i++)
                    {
                        temp[i].ErrorsChanged += RaiseCanExecuteChanged;
                    }
                }
            }
        }

        UpdateAMSCommand.RaiseCanExecuteChanged();
    }

    private void RaiseCanExecuteChanged(object sender, DataErrorsChangedEventArgs e)
    {
        UpdateAMSCommand.RaiseCanExecuteChanged();
    }

    private bool CanUpdateAms()
    {
        foreach (var cao in CustomAMSOffices)
        {
            if (!cao.Check() || cao.HasErrors)
            {
                return false;
            }
        }

        foreach (var cac in CustomAMSContacts)
        {
            if (!cac.Check() || cac.HasErrors)
            {
                return false;
            }
        }
        return true;
    }

编辑: 我使用的relaycommand:https://github.com/briannoyes/WPFMVVM-StarterCode/blob/master/ZzaDashboard/ZzaDashboard/RelayCommand.cs

2 个答案:

答案 0 :(得分:0)

好的,我只是要复制粘贴一些我正在使用的代码,这样你就可以将这些代码弹出到你的项目中并使用。

首先,RelayCommand()课程。我从this msdn page提取了这段代码:

public class RelayCommand : ICommand
{
    #region Fields
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;
    #endregion

    #region Constructors
    public RelayCommand(Action<object> execute) : this(execute, null) { }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }
    #endregion

    #region ICommand Members
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
    #endregion
}

现在,我们的ModelView.cs课程需要继承INotifyPropertyChanged,并且我们会RaisePropertyChanged()。现在我通常只是让它成为一个自己的文件,并让我的所有ModelViews继承它,所以代码更清洁,但你可以随意做。

以下是我如何设置它的方法:

BaseViewModel.cs:

public class BaseViewModel : INotifyPropertyChanged
{
    internal void RaisePropertyChanged(string prop)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    // Any other code we want all model views to have
}

现在,对于我们的MainViewModel.cs,我们将继承BaseViewModel,添加我们的事件处理程序,并运行它!

示例:ServerViewModel.cs

public class ServerViewModel : BaseViewModel
{
    public RelayCommand BroadcastMessageCommand { get; set; }

    private string _broadcastmessage;
    public string broadcastmessage
    {
        get { return _broadcastmessage; }
        set { _broadcastmessage = value; RaisePropertyChanged("broadcastmessage"); }
    }

    Server server;

    public ServerViewModel()
    {
        server = new Server();
        server.run();
        BroadcastMessageCommand = new RelayCommand(BroadcastMessage, CanBroadcast);
    }

    private bool CanBroadcast(object param)
    {
        if (string.IsNullOrWhiteSpace(broadcastmessage))
            return false;
        if (!server.running)
            return false;
        return true;
    }

    public void BroadcastMessage(object param)
    {
        server.BroadcastMessage(broadcastmessage);
        broadcastmessage = "";
        RaisePropertyChanged("broadcastmessage");
    }
}

现在MainView.xaml中与Command="{Binding broadcastmessage}"绑定的任何内容都会相应更新。在我的情况下,我将此绑定到一个按钮,如果消息为空,或者如果我们没有连接到服务器,则按钮将被禁用。

希望有足够的代码示例让您朝着正确的方向前进!如果您对此有任何疑问,请与我联系。

答案 1 :(得分:0)

让我们尽可能地尝试简化代码,直到我们正常工作,然后我们将慢慢添加代码,直到找到导致问题的代码。

所以,让我们减少它的准系统,看看我们是否有任何成功。试试这段代码:

public RelayCommand UpdateAMSCommand { get; private set; }

public AMSSettingsViewModel(IEventAggregator eventAggregator)
{
    UpdateAMSCommand = new RelayCommand(OnUpdateAMS, CanUpdateAms);
    CustomAMSOffices.ListChanged += listChanged;
    CustomAMSContacts.ListChanged += listChanged;
}

private void listChanged(object sender, ListChangedEventArgs e)
{
    UpdateAMSCommand.RaiseCanExecuteChanged();
}

private void RaiseCanExecuteChanged(object sender, DataErrorsChangedEventArgs e)
{
    UpdateAMSCommand.RaiseCanExecuteChanged();
}

// This will simply flip from true to false every time it is called.
private bool _canupdate = false;
private bool CanUpdateAms()
{
    _canupdate = !_canupdate;
    return _canupdate;
}

编辑:我不知道为什么它不起作用。