【问题标题】:How can I extend a ComboBox to support commands (MVVM)?如何扩展 ComboBox 以支持命令 (MVVM)?
【发布时间】:2011-02-24 05:07:18
【问题描述】:

正如主题所说,我需要扩展标准 Silverlight ComboBox 的功能以支持命令。由于我遵循 MVVM,因此我需要我的 ComboBox 将 SelectionChanged 事件传达给我的 ViewModel。

执行此操作的代码会是什么样子?我希望能够将 Command 属性放在我的 ComboBox XAML 控件上。

使用(WCF RIA、MVVM、VB.NET)..

所有提示都已应用!

【问题讨论】:

    标签: vb.net silverlight mvvm combobox command


    【解决方案1】:

    创建一个公开ICommand Commandobject CommandParameter 的行为。在行为连接到 AssociatedObject 的 SelectionChanged 事件。然后您可以将命令绑定到您的行为并为 SelectionChanged 事件模拟命令。

    【讨论】:

      【解决方案2】:

      您可以将 Combobox 的 SelectedIndex 或 SelectedItem 属性绑定到您的 ViewModel。所以你不需要任何命令。

      示例(绑定到 SelectedIndex):

      XAML

      <ComboBox SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}"/>
      

      C#

      public class ComboBoxViewModel
      {
         private int _selectedIndex;
         public int SelectedIndex {
           get { return _selectedIndex; }
           set { 
             if (value != _selectedIndex) {
               _selectedIndex = value;
               // Perform any logic, when the SelectedIndex changes (aka. PropertyChanged-Notification)
             }
           } 
         }
      }
      

      示例(绑定到 SelectedItem):

      XAML

      <ComboBox SelectedItem="{Binding SelectedItem, Mode=TwoWay}"/>
      

      C#

      public class ComboBoxViewModel
      {
         private MyViewModel _selectedItem;
         public MyViewModel SelectedItem {
           get { return _selectedItem; }
           set { 
             if (value != _selectedItem) {
               _selectedItem= value;
               // Perform any logic, when the SelectedIndex changes ((aka. PropertyChanged-Notification)
             }
           } 
         }
      }
      

      【讨论】:

      • 如果您还需要访问当前正在选择的对象,您可以对 SelectedItem 属性执行完全相同的操作。如果出于某种原因您决定要指挥另一个事件,例如 Focus,我会查看 galasoft.ch/mvvm/getstarted/#tutorials,查看 EventToCommand 行为部分。
      • 很好的答案,我会继续尝试
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 2014-06-27
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多