Dynamic ContextMenu In CodeBehind

后端 未结 3 1775
情深已故
情深已故 2021-02-13 14:28

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:

ContextMen         


        
相关标签:
3条回答
  • 2021-02-13 14:48

    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>
    
    0 讨论(0)
  • 2021-02-13 14:49

    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>
    
    0 讨论(0)
  • 2021-02-13 14:58

    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.

    0 讨论(0)
提交回复
热议问题