WPF CommandParameter绑定不更新

Col*_*inE 7 wpf binding command commandparameter

我试图在WPF应用程序中使用Command和CommandParameter与Buttons绑定.我有这个完全相同的代码在Silverlight中工作正常,所以我想知道我做错了什么!

我有一个组合框和一个按钮,其中命令参数绑定到组合框SelectedItem:

<Window x:Class="WPFCommandBindingProblem.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">
    <StackPanel Orientation="Horizontal">
        <ComboBox x:Name="combo" VerticalAlignment="Top" />
        <Button Content="Do Something" Command="{Binding Path=TestCommand}"
                CommandParameter="{Binding Path=SelectedItem, ElementName=combo}"
                VerticalAlignment="Top"/>        
    </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

背后的代码如下:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        combo.ItemsSource = new List<string>(){
            "One", "Two", "Three", "Four", "Five"
        };

        this.DataContext = this;

    }

    public TestCommand TestCommand
    {
        get
        {
            return new TestCommand();
        }
    }

}

public class TestCommand : ICommand
{
    public bool CanExecute(object parameter)
    {
        return parameter is string && (string)parameter != "Two";
    }

    public void Execute(object parameter)
    {
        MessageBox.Show(parameter as string);
    }

    public event EventHandler CanExecuteChanged;

}
Run Code Online (Sandbox Code Playgroud)

使用我的Silverlight应用程序,当组合框的SelectedItem发生更改时,CommandParameter绑定会导致使用当前所选项重新评估我的命令的CanExecute方法,并相应地更新按钮启用状态.

对于WPF,由于某种原因,只有在解析XAML时创建绑定时才会调用CanExecute方法.

有任何想法吗?

Gob*_*lin 8

您需要告诉WPF CanExecute可以更改 - 您可以在TestCommand类中自动执行此操作,如下所示:

public event EventHandler CanExecuteChanged
{
    add{CommandManager.RequerySuggested += value;}
    remove{CommandManager.RequerySuggested -= value;}
}
Run Code Online (Sandbox Code Playgroud)

每当属性在视图中发生更改时,WPF都会询问CanExecute.