我正在尝试在 WPF 应用程序中将 Command 和 CommandParameter 绑定(bind)与按钮一起使用。我有这个完全相同的代码在 Silverlight 中工作得很好,所以我想知道我做错了什么!
我有一个组合框和一个按钮,其中命令参数绑定(bind)到组合框 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 绑定(bind)会导致我的命令的 CanExecute 方法使用当前选定的项目重新评估,并且按钮启用状态也会相应更新。
使用 WPF,由于某种原因,CanExecute 方法仅在解析 XAML 时创建绑定(bind)时调用。
有任何想法吗?
最佳答案
您需要告诉 WPF CanExecute 可以更改 - 您可以在 TestCommand 类中自动执行此操作,如下所示:
public event EventHandler CanExecuteChanged
{
add{CommandManager.RequerySuggested += value;}
remove{CommandManager.RequerySuggested -= value;}
}
然后,每当 View 中的属性发生更改时,WPF 都会询问 CanExecute。
关于WPF CommandParameter 绑定(bind)未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3092339/