Tuesday, August 28, 2012

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

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

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 the Command attribute on my ComboBox XAML control.

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

All tips appricated!

Answers & Comments...

Answer: 1

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.

by : Stephanhttp://stackoverflow.com/users/58659

Answer: 2

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)        }      }     } } 
by : Jehofhttp://stackoverflow.com/users/83039




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog