views:

543

answers:

2

I have a WPF ListView control with a ContextMenu written in XAML Code. With every right-click on the ListView the ContextMenu is shown even when there are no items in the ListView.

This is a behavior I don't want. The ContextMenu should only open if there are items in the ListView. I have no problem counting the items but I don't find the right event to suppress the ContextMenu.

How can I do that?

A: 

My WPF skills are still at the novice level, so this may not be the best answer.

I would bind the ListView ContextMenu property to a property in the code-behind. This property could check your listbox and return either null or the appropriate context menu as needed. Since this is all based on view level details it does not touch your business logic and results in the behavior you want.

Let me know if you want a code sample for this approached

RB Davidson
+3  A: 

Handle the ContextMenuOpening event of the ListView to cancel the menu if the list is empty :

    private void listView_ContextMenuOpening(object sender, ContextMenuEventArgs e)
    {
        if (listView.Items.Count == 0)
            e.Handled = true;
    }
Thomas Levesque
+1 For having a better and simpler answer than mine.
RB Davidson
Thanks. It's working like it should.
Holli