7

我正在使用 MVVM-Light 并且我的中继命令运行良好,我刚刚读到我应该实施CanExecuteChangedCanExecute. 虽然我找不到一个很好的例子。

有没有人有一个很好的例子来说明如何实现这些。

CanExecute 在无法执行时需要返回 False 但不会只是禁用按钮?

我什么时候执行CanExecuteChanged

任何人都有任何关于何时使用每一个的好例子,我的代码没有,但这篇博客文章指出我应该实现这些项目。

我有点困惑,正如我所说,我认为我只是将Enabled属性或某些东西绑定到 ViewModel 中的属性,以便我可以禁用按钮或类似控件?

任何有助于理解的帮助将不胜感激。

编辑

这就是我现在所拥有的......它可以工作,但按钮并没有物理禁用,只有命令没有运行,因为我返回 false。我在构造函数中调用 CanExecuteMe 以强制 RaiseCanExecuteChanged 运行...

这在我的视图模型的构造器中运行

        this.Page2Command = new RelayCommand(() => this.GoToPage2(), () => CanExecuteMe);

        CanExecuteMe = false;

这是我的其余代码,我从一个例子中得到它。

    private bool _canIncrement = true;

    public bool CanExecuteMe
    {
        get
        {
            return _canIncrement;
        }

        set
        {
            if (_canIncrement == value)
            {
                return;
            }

            _canIncrement = value;

            // Update bindings, no broadcast
            //RaisePropertyChanged(CanIncrementPropertyName);

            Page2Command.RaiseCanExecuteChanged();
        }
    }

    public RelayCommand Page2Command
    {
        get;
        private set;
    }

    private object GoToPage2()
    {
        System.Windows.MessageBox.Show("Navigate to Page 2!");
        return null;
    }

这是我的 XAML

  <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="31,77,0,0" x:Name="button1" VerticalAlignment="Top" Width="75" >
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding Page2Command, Mode=OneWay}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
4

2 回答 2

10

当 Button 需要确定是否应该启用它时调用 CanExecute。

Button 在绑定时执行此操作,并且在每次 CanExecuteChanged 触发后(Button 侦听此事件以获取其命令)。

所以,如果按钮应该被禁用,你应该触发 CanExecuteChanged,当按钮调用 CanExecute 时,你应该返回false. 这是使用命令绑定时启用/禁用按钮的首选方法。

命令绑定使您能够将所有按钮逻辑封装在一个实例(命令)中。CanExecute 方法应查询应用程序的当前状态以确定是否应启用或禁用按钮。通过这种封装,您可以减少 View Model 中的意大利面条式代码,这些检查在这里和那里和那里执行,我忘记了那里的那个。

于 2011-05-03T13:56:03.667 回答
1

您应该非常小心地使用 CanExecute 谓词。它会检查每个 UI 更改以及输入到 ANY 字段中的每个键盘键。

这可能会导致性能问题!

于 2013-06-27T09:45:38.357 回答