开发者

How can I extend a ComboBox to support commands (MVVM)?

开发者 https://www.devze.com 2022-12-31 22:23 出处:网络
As topic says, I need to extend the features of a standard Silverlight ComboBox to also support Commanding. Since I follow MVVM I need my ComboBox to communicate the SelectionChanged event to my ViewM

As topic says, I need to extend the features of a standard Silverlight ComboBox to also support Commanding. Since I follow MVVM I need my ComboBox to communicate the SelectionChanged event to my ViewModel.

What would the code look like for doing this? I want to be able to put th开发者_如何学JAVAe Command attribute on my ComboBox XAML control.

Using (WCF RIA, MVVM, VB.NET)..

All tips appricated!


You can bind the property SelectedIndex or SelectedItem of the Combobox to your ViewModel. So you don´t need any Commands.

Example (Binding to 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)
       }
     } 
   }
}

Example (Binding to 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)
       }
     } 
   }
}


Create a behavior that exposes an ICommand Command and a object CommandParameter. In the behavior wire up to the SelectionChanged event of your AssociatedObject. Then you can bind the command to your behavior and simulate a command for the SelectionChanged event.

0

精彩评论

暂无评论...
验证码 换一张
取 消