【问题标题】:RaiseCanExecuteChanged not Working In Compiled exe But Does Work when DebuggingRaiseCanExecuteChanged 在编译的 exe 中不起作用,但在调试时起作用
【发布时间】:2015-07-11 22:19:53
【问题描述】:

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

背景:使用 Prism 框架

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

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

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


编辑:当我第一次通过 .exe 打开应用程序时,会调用 RaiseCanExecuteChanged(因为我在 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}">

我什至绝望了,并尝试在我的 Button 中添加一个 IsEnabled 属性,我绑定到 CanExecuteButton ... 无济于事。

【问题讨论】:

  • 你能把ButtonCommand的代码贴出来吗?
  • 已解决,但我不知道为什么。它现在正在工作......

标签: c# wpf mvvm prism delegatecommand


【解决方案1】:

试试

Command="{Binding DataContext.ButtonCommand,RelativeSource={RelativeSource FindAncestor, AncestorType=YourView}}" CommandParameter="{Binding}" 

【讨论】:

    【解决方案2】:

    我遇到过类似的问题,即未调用 Prism DelegateCommand.CanExeuteChanged 事件。通过查看源代码,看起来这是因为它不依赖于 CommandManager.RequerySuggested

    尝试在 CanExecuteChanged 事件如下所示的位置创建自己的命令:

    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 
    }
    

    现在,如果 WPF 检测到 UI 中的更改,那么 CommandManager 将在该命令上调用 CanExecute。如果应用程序的机房发生变化,您可以调用RaiseCanExecuteChanged 来更新 CanExecute。

    【讨论】:

    • 这似乎没有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多