我正在尝试在 WPF 应用程序中将 Command 和 CommandParameter 绑定与按钮一起使用。我有这个完全相同的代码在 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>
后面的代码如下:
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;
}
对于我的 Silverlight 应用程序,当组合框的 SelectedItem 更改时,CommandParameter 绑定会导致我的命令的 CanExecute 方法使用当前选定的项目重新评估,并且按钮启用状态也会相应更新。
使用 WPF,由于某种原因,CanExecute 方法仅在解析 XAML 时创建绑定时调用。
有任何想法吗?