鉴于以下 XAML...
<ComboBox x:Name="advisoriesComboBox"
DisplayMemberPath="Name"
ItemsSource="{Binding Path=Advisories}"
SelectedItem="{Binding Path=SelectedAdvisory}" />
<Button Command="{Binding Path=AddAdvisoryCommand}"
CommandParameter="{Binding ElementName=advisoriesComboBox, Path=SelectedItem}"
CommandTarget="{Binding ElementName=advisoriesComboBox}"
Content="Add..." />
我正在寻找一种绑定(bind) ComboBox、Button 和 Command 的方法,以便当 ComboBox 的值更改时,在 Command 上调用 CanExecute。我想要的最终效果是能够根据列表中选择的项目来启用和禁用按钮,我更愿意使用 ICommand 接口(interface)来执行此操作。
我过去曾通过在虚拟机上使用“SelectedAdvisory”属性并在命令对象上手动调用 RaiseCanExecuteChanged 来完成此操作(我正在使用 PRISM v4 中的 DelegateCommand 实例),但我确信有一个更好、更干净的方法仅使用 XAML 来执行此操作的方法。
谢谢。
编辑:此外,是否有更简单的方法从按钮引用组合框?我尝试使用RelativeSource PreviousData,但无法让它工作,因此使用x:Name
。
再次感谢。
最佳答案
我会在 View 模型中完成所有操作,在我看来,在单元测试方面是最好的
<ComboBox x:Name="advisoriesComboBox"
DisplayMemberPath="Name"
ItemsSource="{Binding Path=Advisories}"
SelectedItem="{Binding Path=SelectedAdvisory}" />
<Button Command="{Binding Path=AddAdvisoryCommand}"
Content="Add..." />
虚拟机
private bool CanAddExecute()
{
return this.SelectedAdvisory != null;
}
private void AddExecute()
{
if(!CanAddExecute())
return;
//do here what you want, your information for the selected item is in this.SelectedAdvisory
}
代码是手写的,因此可能会有一些错误。
关于wpf - 组合框、按钮和 ICommand 绑定(bind)(MVVM 式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9211531/