Mar 17 2009

How to create an attached property in WPF using a ComboBox

Category: WPF | C#fossmo @ 17:37

This is mostly a note to myself on how to create an attached property in WPF using a ComboBox.

public class SelectionBehavior
{
    public static DependencyProperty SelectionChangedProperty =
            DependencyProperty.RegisterAttached("SelectionChanged",
            typeof(ICommand),
            typeof(SelectionBehavior),
            new UIPropertyMetadata(SelectionBehavior.SelectedItemChanged));
    public static void SetSelectionChanged(DependencyObject target, ICommand value)
    {
        target.SetValue(SelectionBehavior.SelectionChangedProperty, value);
    }
    private static void SelectedItemChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        Selector element = target as Selector;
        if (element == null) throw new InvalidOperationException("This behavior can be attached to Selector item only.");
        if ((e.NewValue != null) && (e.OldValue == null))
        {
            element.SelectionChanged += SelectionChanged;
        }
        else if ((e.NewValue == null) && (e.OldValue != null))
        {
            element.SelectionChanged -= SelectionChanged;
        }
    }
    private static void SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        UIElement element = (UIElement)sender;
        ICommand command = (ICommand)element.GetValue(SelectionBehavior.SelectionChangedProperty);
        command.Execute(((Selector) sender).SelectedValue);
    }
}

And in the XAML file add

<ComboBox local:SelectionBehavior.SelectionChanged="{Binding MyCommand}"  
              ItemsSource="{Binding MySource}"
              Name="MyComboBox"/> 

 

MyCommand can be a DelegateCommand from CAG.

Tags:

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Comments are closed