尽管绑定命令的CanExecute为false,但为什么按钮保持启用状态

时间:2015-01-23 13:48:22

标签: c# wpf mvvm mvvm-light

我有一个带ICommand的ViewModel:

class MainWindowViewModel : ViewModelBase
{
    public bool CanExecute { get; set; }

    public ICommand SomeCommand { get; set; }

    public MainWindowViewModel()
    {
        CanExecute = true;

        SomeCommand = new RelayCommand(() => MessageBox.Show("Executing"), () => CanExecute);

        CommandManager.RequerySuggested += OnRefreshing;
    }

    private void OnRefreshing(object sender, EventArgs e)
    {
        Console.WriteLine("Refreshing");
    }
}

我在XAML中有一个非常简单的绑定:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <CheckBox Grid.Row="0" IsChecked="{Binding CanExecute, Mode=TwoWay}"/>
        <Button Grid.Row="1" Content="Click Me!" Command="{Binding SomeCommand}"/>
    </Grid>
</Window>

当我点击CheckBox时,CanExecute应该改变。我可以看到CommandManager.RequerySuggested被抛出,但我的按钮保持启用状态。

怎么了?我的约束力?这与MVVMLight有什么关系吗?

1 个答案:

答案 0 :(得分:2)

问题在于MVVMLight框架。其RelayCommand已更改,不再听CommandManager.RequerySuggested。所以你实际上必须在命令上手动调用RaiseCanExecuteChanged。这很糟糕......

有关MVVMLight中此更改的讨论,请参阅here

任何想法,如何在没有大量手动拨打RaiseCanExecuteChanged的情况下处理此问题将非常感谢!