Search code examples
wpfcomboboxicommandrelaycommand

WPF ICommand Implementation for ComboBoxItem


How can I implement ICommand in WPF(4.5) ComboBoxItem? I tried CommandBinding but I getting error message "Command' property of type 'CommandBinding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject"


Solution

    1. Add Reference to System.Windows.Interactivity as shown below enter image description here
    2. Then in Windows.xaml add below line . This will add reference to XAML

      xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"   
      

    and your XAML will be like as given below enter image description here

    And your Combobox XAML be like : -

    <ComboBox Name="myComboBox" SelectedValuePath="Content">
            <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding YourCommandName}" 
                 CommandParameter="{Binding ElementName=myComboBox, 
                  Path=SelectedValue}"/>
            </i:EventTrigger>
         </i:Interaction.Triggers>
         <ComboBoxItem Content="ItemOne" />
         <ComboBoxItem Content="ItemTwo" />
         <ComboBoxItem Content="ItemThree" />
    </ComboBox>