Passing DropDown SelectedValue as a CommandParameter to ViewModel using MVVMLight in Silverlight

Hi there,
This article will explain how someone send the selected value of drop down as a command parameter to your view model.

Intro:
I ran into a situation where on selection change of drop down will cause population of bonded data grid's cells. I was able to get the selected row but the issue was that i got the previously selected value not the latest, so in that case this approach works fine.

Let's start.....

1. These namespaces need to be added at the top of your silverlight user control

xmlns:i1="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL4"

2. Insert below code in XAML file like:

<Combo Box ............................... >
Code here
</Combo Box>
and code to be added is:


<i1:Interaction.Triggers>
     <i1:EventTrigger EventName="SelectionChanged">
           <cmd:EventToCommand Command="{Binding Path=rlcLPriceChanged, Source={StaticResource dVM}}"
                     PassEventArgsToCommand="True"
                     MustToggleIsEnabledValue="True"/>
         </i1:EventTrigger>
 </i1:Interaction.Triggers>


EventName: Event on which you need to perform your action
Command: Command name with that you bind this event
Source: Your view-model key
PassEventArgsToCommand:  By setting this property to True, you are telling to send the EventArgs along with command, as we use them to get the Selected-value.


3. Now you need to do some coding in View-Model

Write a property that will get you the command along with the method to be executed.

public RelayCommand<object> rlcLPriceChanged
        {
            get
            {
                return new RelayCommand<object>((o) => GetListPrice(o));
            }
        }


As we are sending EventArgs so we need to give RelayCommand a type so that it knows something is coming :)
We pass that EventArgs to our function that will be executed.

4. In our function we do something like:

private void GetListPrice(object o)
 {
              SelectionChangedEventArgs e = (SelectionChangedEventArgs)o;

              clsCheckedListBox cclb = (clsCheckedListBox)e.AddedItems[0];
              string LPNo = cclb.Value;
  }

Few things needs clarification:

clsCheckedListBox: is a class whose type of ObservableCollection is bind to my ComboBox
AddedItems[]: returns an array of selected items of a collection and it returns the collection type object with which the DropDownList is bonded.

As in my case selected item is single so i gave the index to get it.
Hope it will help you guys, as it is my first post so i encourage your suggestions so i can improve my way of explaining things.

Comments

Popular Posts