tags:

views:

40

answers:

1

I have simple scenario in which i hide and show a signle MenuItem in a contextmenu as shown below:

Xaml:

<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.ContextMenu>
    <ContextMenu Name="mainMnu">
        <MenuItem Name="mnu" Header="Testing"/>
    </ContextMenu>
</Window.ContextMenu>

<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <Button HorizontalAlignment="Left" Margin="52,131,0,108" Name="Button1" Width="75">Button</Button>
</Grid>

code behind:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
    If mnu.Visibility = Windows.Visibility.Visible Then
        mnu.Visibility = Windows.Visibility.Collapsed
        mainMnu.Visibility = Windows.Visibility.Collapsed
    Else
        mnu.Visibility = Windows.Visibility.Visible
        mainMnu.Visibility = Windows.Visibility.Visible
    End If

End Sub

The Problem is that every other time i press the button the menuitem is not shown. Right click only shows a small empty rectangle. (like there is a visible menu, but not a visible menuitem). It somehow works in a cycle... first 2 clicks: problem, next 2 clicks ok, and so on...

Any ideas?

+1  A: 

If you're trying to disable the context menu, setting its Visibility is the wrong way to do it.

Instead, you should set the ContextMenu property to Nothing.

For example:

If ContextMenu Is Nothing Then
    ContextMenu = mainMnu
Else
    ContextMenu = Nothing
End If
SLaks
That works fine for my example... But i still wonder if there is a way for a Contextmenu to not fire at all if it doesnt have any visible menuitems attached.
Entrodus
Since you have control over your menuitems via codebehind, can you use the setting of their visibility to either disable or enable the contextmenu? i.e. when you create your window, set it to null, and when you make a menuitem visible, set it to mainMnu? The obvious problem here is that you might dynamically make things visible or invisible, and therefore you'd have to track it.I was looking into seeing if the ContextMenu appears via an event. I hoped that you could handle the tunneling event by checking for child menuitem visibility, and then set the envent to Handled, but came up short.
Dave