1

我完全知道是什么原因造成的。

背景:使用 Prism 框架

  1. 我有一个按钮绑定到DelegateCommand
  2. 我打电话RaiseCanExecuteChanged

当我在 Visual Studio 中以调试模式启动应用程序时,一切正常。该应用程序运行完美。

然后当我通过 .exe 打开应用程序时,RaiseCanExecuteChanged没有调用该方法。我不知道为什么会这样。还有其他人遇到类似的问题吗?


编辑:当我第一次通过 .exe 打开应用程序时,RaiseCanExecuteChanged会调用它(因为我在 my 的构造函数中设置了它ViewModel)。但是,它再也不会被调用。


需要时的代码:

private readonly DelegateCommand _buttonCommand;

public ViewModel()
{
    _buttonCommand = new DelegateCommand(Button, CanExecuteButton);
}

public DelegateCommand ButtonCommand
{
    get { return this._buttonCommand; }
}

public void Button()
{
    ... do stuff ...
    _buttonCommand.RaiseCanExecuteChanged();
}

public bool CanExecuteButton()
{
    if (some condition)
        return true;
    else
        return false;
}

<Button x:Name="MyButton" Content="ClickMe"
        Command="{Binding ButtonCommand}">

我什至绝望了,并试图IsEnabled在我的 Button 中放置一个属性,但我必须CanExecuteButton……但无济于事。

4

2 回答 2

0

I've experienced similar issues with the Prism DelegateCommand.CanExeuteChanged event not being invoked.. By looking into the source code it looks like it is because it does not rely on the CommandManager.RequerySuggested.

Try making your own command where the event CanExecuteChanged is like so:

public RelayCommand : ICommand
{
    private event EventHandler _canExecuteChanged;
    public event EventHandler CanExecuteChanged
    {
        add
        {
            CommandManager.RequerySuggested += value;
            _canExecuteChanged += value;
        }
        remove
        {
            CommandManager.RequerySuggested -= value;
            _canExecuteChanged -= value;
        }
    }

    public void RaiseCanExecuteChanged()
    {
        var handler = _canExecuteChanged;
        if (handler != null)
            handler(this, EventArgs.Empty);

    }

    // All the other stuff also 
}

Now, if WPF detects changes in the UI then the CommandManager will invoke CanExecute on the command. And if something in the engineroom of the application changes, then you can invoke RaiseCanExecuteChanged to update CanExecute.

于 2015-05-02T08:05:54.583 回答
0

尝试

Command="{Binding DataContext.ButtonCommand,RelativeSource={RelativeSource FindAncestor, AncestorType=YourView}}" CommandParameter="{Binding}" 
于 2016-10-13T13:09:39.593 回答