yu_ominae
yu_ominae

Reputation: 2935

WPF context menu doesn't stay open

In WPF I am trying to put a context menu on the items of a listbox. When I run my app and right click on an item of the listbox the menu pops up for a split second and then closes again. I just can't figure out what I am doing wrong.

This is the code I am using:

<ListBox Grid.Column="0" Name="lsbAddedElements" Width="150" Margin="3,3,3,3"
         SelectionMode="Multiple">
  <ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
      <Setter Property="ContextMenu">
        <Setter.Value>
          <ContextMenu>
            <MenuItem Header="Delete" Click="btnDeleteElement_Click"></MenuItem>
          </ContextMenu>
        </Setter.Value>
      </Setter>
    </Style>
  </ListBox.ItemContainerStyle>
</ListBox>

The listbox is bound to an ObservableCollection in code when the window is initialised, so item management is taken care of in code behind.

UPDATE:

I might need to add that thsi is part of an adin I am making for Excel. I am connecting to Excel using ExcelDNA then passsing the handle on to the WPF window that this code snippet is part of. Could this be a reason for the context menu behaving in an unexpected way?

Upvotes: 1

Views: 1337

Answers (1)

Per
Per

Reputation: 1061

I think the problem is that the listbox item is getting focused. A simple solution to your problem is to set the context menu on the list box and enable/disable context menu items if the list box has a selected item.

Upvotes: 2

Related Questions