WPF: exception if I add an event handler in MenuItem (in ListBox)

I need the context context for the ListBoxItems list. So I created this:

<ListBox Name="listBoxName">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding UserName}" />
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                    <ListBox.ItemContainerStyle>
                        <Style TargetType="ListBoxItem">
                            <Setter Property="ContextMenu">
                                <Setter.Value>
                                    <ContextMenu>
                                        <MenuItem Header="View" Name="MenuItemView" />
                                    </ContextMenu>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </ListBox.ItemContainerStyle>
                </ListBox>

This works great. I have contextmenu for all elements, but if I want to add a click-eventhandler to menuitem, like this:

<MenuItem Header="View" Name="MenuItemView" Click="MenuItemView_Click" />

I get a XamlParseException when creating a window.

InnerException: The System.Windows.Controls.MenuItem object cannot be converted to the System.Windows.Controls.Grid type

It throws only an exception if I add an event handler. The event method is empty.

Edit: Stacktrace of InnerException:

in Chat_Client.ChatWindow.System.Windows.Markup.IComponentConnector.Connect (Int32 connectionId, Object target) in C: \ XXX \ Chat_Client \ ChatWindow.xaml: Row 19.

MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetConnectionId( root, Int32 connectionId, Object )

Edit2: , , . :

//MenuItem s = sender as MenuItem;
//ContextMenu cm = s.Parent as ContextMenu;
//Popup pu = cm.Parent as Popup;
//object o = pu.Parent;

Popup NULL. selectedItem ListBox. , ListBoxRow Contextmenu?

+3
1

VS2010 WPF4.

, , :

<Window.Resources>
    <ContextMenu x:Key="ListBoxItemContextMenu">
        <MenuItem Header="View" Name="MenuItemView" Click="MenuItemView_Click"/>
    </ContextMenu>
</Window.Resources>

, :

<Setter Property="ContextMenu" Value="{StaticResource ListBoxItemContextMenu}"/>

:

private void MenuItemView_Click(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("Clicked!");
}
+4

Source: https://habr.com/ru/post/1782713/


All Articles