7
我想要在WPF应用程序中使用Command和CommandParameter绑定按钮。我有这个完全相同的代码在Silverlight中工作得很好,所以我想知道我做错了什么!WPF CommandParameter绑定不更新
我有一个组合框和一个按钮,其中命令参数绑定到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,出于某种原因,CanExecute方法仅在分析XAML时创建绑定时才会调用。
任何想法?
这将重新评估UI上所有属性更改的所有命令?并没有办法与委托命令一起使用它? Silverlight中没有简单的或者不合适的解决方案吗? – Firo 2013-01-18 15:15:56
这只是最简单的方法 - 你控制何时调用CanExecuteChanged事件 - 在这里我只是设置它来更新,只要框架决定它可能已经更新。 – Goblin 2013-01-21 07:50:05