Showing posts with label Silverlight. Show all posts
Showing posts with label Silverlight. Show all posts

Monday, January 9, 2012

Execute Command on ComboBox Selection changed

If you are developing WPF application MVVM way you might have noticed that Button Provide a Command property that can be set to a ICommand instance and the command will be executed when button is clicked. There is no inbuilt way to set a Command that can be executed when ComboBox selection is changed. I have coded a behaviour that can be used to achieve this. Below is the code for the behaviour.

using System.Windows.Input;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
public class SelectionChangedBehaviour
{
 
public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand),
  typeof(SelectionChangedBehaviour), new PropertyMetadata(PropertyChangedCallback));

  public static void PropertyChangedCallback(DependencyObject depObj, DependencyPropertyChangedEventArgs args)
  {
   
Selector selector = (Selector)depObj;
    if (selector != null)
    {
      selector.SelectionChanged +=
new SelectionChangedEventHandler(SelectionChanged);
    }
  }


 
public static ICommand GetCommand(UIElement element)
  {
   
return (ICommand)element.GetValue(CommandProperty);
  }

 
public static void SetCommand(UIElement element, ICommand command)
  {
    element.SetValue(CommandProperty, command);
  }

  private static void SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
   
Selector selector = (Selector)sender;
    if (selector != null)
    {
     
ICommand command = selector.GetValue(CommandProperty) as ICommand;
      if (command != null)
      {
        command.Execute(selector.SelectedItem);
      }
    }
  }
}


Set the command in xaml as shown below:

<ComboBox SelectionChangedBehaviour.Command="{Binding CommandImpl}">ComboBox>

This can be used for ListBox and ListView as well.

Type based templating

            <DataTemplate DataType="{x:Type vm:SampleViewModel}">                 <DataTemplate.Resources>       ...