WPF命令参数绑定不更新
-
29-09-2019 - |
题
我正在尝试将命令和命令参数计与WPF应用程序中的按钮绑定。我拥有完全相同的代码在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应用程序中,作为Combobox的SelectedItem的更改,命令参数绑定会导致我的命令与当前选择的项目重新评估CANECECUTE方法,并相应地更新了启用按钮的状态。
使用WPF,由于某种原因,仅在解析XAML时创建绑定时才调用CANECECUTE方法。
有任何想法吗?
解决方案
您需要告诉WPF CANEXECUTE可以更改 - 您可以在这样的testCommand类中自动执行此操作:
public event EventHandler CanExecuteChanged
{
add{CommandManager.RequerySuggested += value;}
remove{CommandManager.RequerySuggested -= value;}
}
然后,WPF每次属性在视图中更改时都会询问CANECECTUCE。
不隶属于 StackOverflow