LazyZebra
LazyZebra

Reputation: 1113

WPF MVVM - Binding highlighted item in Combobox

Is there a way to bind a highlighted ComboBox item in WPF/MVVM?

The reason I want this behavior is that I want to be able to right-click on a ComboBox item and pass the argument (Item Id for that matter) in the CommandParameter.

Since no item is actually selected until I left-click on the item, I have no args to pass...

Thoughts please?

<ComboBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete Expense Category" Command="{Binding DeleteMenuItemCommand}"
CommandTarget="{Binding HighlightedExpenseCategory}" CommandParameter="{Binding Id}"></MenuItem>
</ContextMenu>
</ComboBox.ContextMenu>

Upvotes: 1

Views: 868

Answers (1)

Fise
Fise

Reputation: 66

First a question: what is your ultimate goal and can you approach it without having the user right click on a context menu item? Perhaps what you may want is a hierarchical combobox like in the image here Any ideas how to implement ComboBox to represent hierarchical data? . Though that may not suit you if you indeed just want to perform an action on an item in your combo box.

With that aside, then HighCore put you on the right track (sorry HighCore, I'm going to steal a little of your thunder here, but as a consolation I'm giving you a couple votes). The key thing is that the ContextMenu is a property of the ComboBoxItem and not the ComboBox itself.

This code snippet may help you get a step closer, though I haven't tested beyond XamlPad. You'll likely have an additional step of making sure your bindings can reach your view model with the command as well as your menu item's Id property, wherever you've defined that. Try the Binding's RelativeSource, but come back if you need help with that. Good luck!

<ComboBox>
   <ComboBox.Resources>
          <ContextMenu x:Key="contextMenu">
             <MenuItem Header="Delete Expense Category" Command="{Binding DeleteMenuItemCommand}"
              CommandTarget="{Binding HighlightedExpenseCategory}" CommandParameter="{Binding Id}" />
          </ContextMenu>
   </ComboBox.Resources>

   <ComboBox.ItemContainerStyle>
      <Style TargetType="{x:Type ComboBoxItem}">
         <Style.Setters>
            <Setter Property="ContextMenu" Value="{StaticResource contextMenu}" />
         </Style.Setters>
      </Style>
   </ComboBox.ItemContainerStyle>
   <ComboBoxItem Content="1" />
   <ComboBoxItem Content="2" />
</ComboBox>

Upvotes: 2

Related Questions