Dynamic ContextMenu In CodeBehind

我们两清 提交于 2020-01-22 13:38:26

问题


I just want to add ContextMenu for several objects that I create dynamically, but The only way I found is to create ContextMenu in runtime like this:

ContextMenu pMenu = new ContextMenu();
MenuItem item1  = new MenuItem();
MenuItem item2  = new MenuItem();

//I have about 10 items
//...
item1.Header = "item1";
item1.Click += new RoutedEventHandler(item1_Click);
pMenu.Items.Add(item1);

item2.Header = "item2";
item2.Click += new RoutedEventHandler(item2_Click);
pMenu.Items.Add(item2);

//and so on

It works, however, in WinForms I was able to drop ContextMenuStrip component to my form and define items and events very quickly w/o writing any code. Is it possible in WPF?


回答1:


You can define your ContextMenu in resources and bind it to any control you needed. Check this out:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ContextMenu x:Key="MyContextMenu">
            <MenuItem Header="Send" />
        </ContextMenu>
    </Window.Resources>
    <Grid>
        <Button Name="a_button"
            ContextMenu="{StaticResource MyContextMenu}" >
        </Button>
    </Grid>
</Window>



回答2:


Additionaly you can put commands on the menuItem...

Like this:

<MenuItem Header="MyContextMenuItem
                  Command="{Binding Path=MyCommand}"
                  CommandTarget="{Binding 
                              RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type DataGrid}}}">

CommandTarget can be very important, if you use your contextMenu on different controls. I often use the FindAncestor here, to identify the caller.




回答3:


The following code works for me, InsertQuery/DeleteQuery are two ICommand methods defined in ViewModel.

  <DataGrid.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Insert"
                      Command="{Binding DataContext.InsertQuery, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/>
            <MenuItem Header="Delete" 
                      Command="{Binding DataContext.DeleteQuery, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/>
        </ContextMenu>
  </DataGrid.ContextMenu>


来源:https://stackoverflow.com/questions/7582552/dynamic-contextmenu-in-codebehind

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