我正尝试在WPF应用程序中使用带有按钮的命令和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,由于某些原因,只有在分析XAML时创建绑定时才会调用CanExecute方法。
有什么想法吗?
发布于 2010-06-22 20:05:57
您需要告诉WPF CanExecute可以更改-您可以在您的TestCommand类中自动执行此操作,如下所示:
public event EventHandler CanExecuteChanged
{
add{CommandManager.RequerySuggested += value;}
remove{CommandManager.RequerySuggested -= value;}
}然后,每当视图中的属性发生变化时,WPF都会询问CanExecute。
https://stackoverflow.com/questions/3092339
复制相似问题