wpf - 组合框、按钮和 ICommand 绑定(bind)(MVVM 式)

标签 wpf binding icommand

鉴于以下 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/

相关文章:

wpf - 在 WPF 中,查看图像的一部分

c# - 禁用 WPF 窗口焦点

wpf - ReadWrite 和 ReadOnly 数据网格绑定(bind)到共享源,导致 ReadWrite 不是正确的 ReadWrite?

android - 在哪个上下文中 ICommand 和 Local :Mvx are prefered

wpf - 标记中 WPF 控件的命名

java - 使用接口(interface)在 java 中运行时绑定(bind)

.net - 绑定(bind)到中继器时注入(inject)当前项目的索引

wpf - 将 ValidationRules 添加到单个 xaml 行或简写 ValidationRules

c# - ICommand MVVM 实现

c# - 为什么wpf控件只有一个命令? (MVVM)