我试图在WPF应用程序中使用命令和commandParameter绑定按钮。我有这个完全相同的代码在Silverlight中工作得很好,所以我想知道我做错了什么!
我有一个组合框和一个按钮,其中命令参数绑定到ComboBox 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,出于某种原因,只有在分析XAML时创建绑定时才调用CanExecute方法。
有什么想法吗?