C# WPF Context menu item click event returns null

感情迁移 提交于 2019-12-24 06:31:24

问题


I'm using WPF with C#. I have a grid of buttons and I've assigned a context menu to each button if it's right-clicked. Right-clicking the buttons works fine and the context menu shows up but clicking the menu items gives a null sender. What could be wrong? Here is the relevant code embedded into the Window XAML code:

 <Window.Resources>
    <ContextMenu x:Key="cmButton">
        <MenuItem Header="Copy" Click="Copy_Click" />
        <MenuItem Header="Cut" />
        <Separator />
        <MenuItem Header="Paste" Click="Paste_Click" />
    </ContextMenu>
 </Window.Resources>

And here is the relevant C# code:

public void WarpHeadCell_RightClick(DraftWindow w, Button b)
    {
        ContextMenu cm = w.FindResource("cmButton") as ContextMenu;
        cm.PlacementTarget = b;
        cm.IsOpen = true;         
    } 

 private void Copy_Click(object sender, RoutedEventArgs e)
   {
       MenuItem mi = e.OriginalSource as System.Windows.Controls.MenuItem;
       ContextMenu cm = mi.ContextMenu;
       Button b = (Button)cm.PlacementTarget;   
   }

mi is always null, does anybody have a clue?


回答1:


I don't see any reason why mi would be null, but you haven't included everything, so I'm going out on a limb here and guessing that mi.ContextMenu is where you are running into a problem. The menu item itself doesn't have a ContextMenu, but it does have a Parent property, which is the ContextMenu it belongs to and is probably what you are looking for.

private void Copy_Click(object sender, RoutedEventArgs e)
{
    MenuItem mi = sender as MenuItem;
    ContextMenu cm = mi.Parent as ContextMenu;
    Button b = cm.PlacementTarget as Button;
}



回答2:


This is my XAML:

   <Window.Resources>
        <ContextMenu x:Key="cmButton">
            <MenuItem Click="Copy_Click" Header="Copy" />
            <MenuItem Header="Cut" />
            <Separator />
            <MenuItem Click="Paste_Click" Header="Paste" />
        </ContextMenu>
    </Window.Resources>
    <Grid>
        <Button Content="SS" ContextMenu="{StaticResource cmButton}" />
    </Grid>

This is my code:

   private void Paste_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem)
            {
                Debug.WriteLine("Ok");
            }

            if (e.OriginalSource is MenuItem menuItem2)
            {
                Debug.WriteLine("Ok");
            }
        }

It works, menuItem and menuItem2 is not null You can download my rar here: https://1drv.ms/u/s!AthRwq2eHeRWiOkw6MHXelG-ntjaDQ



来源:https://stackoverflow.com/questions/48452760/c-sharp-wpf-context-menu-item-click-event-returns-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!