Adding different context menu for datagrid's header

前端 未结 2 1622
悲哀的现实
悲哀的现实 2021-01-15 05:23

I want to add a different context menu for my datagrid\'s header on WPF. How can I do that?

相关标签:
2条回答
  • 2021-01-15 06:02

    You can create a Context Menu for your Data Grid Column Headers or for your Data Grid Rows using DataGrid.ColumnHeaderStyle or DataGrid.RowStyle, respectively. See example:

    <Window.Resources>
        <ContextMenu x:Key="ColumnHeaderMenu">
            <MenuItem Header="Header Option 1"/>
            <MenuItem Header="Header Option 2"/>
        </ContextMenu>
        <ContextMenu x:Key="RowMenu">
            <MenuItem Header="Row Option 1"/>
            <MenuItem Header="Row Option 2"/>
        </ContextMenu>
    </Window.Resources>
    <Grid>
        <DataGrid ItemsSource="{Binding memberList}" AutoGenerateColumns="True">
            <DataGrid.ColumnHeaderStyle>
                <Style TargetType="DataGridColumnHeader">
                    <Setter Property="ContextMenu" Value="{StaticResource ColumnHeaderMenu}"/>
                </Style>
            </DataGrid.ColumnHeaderStyle>
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="ContextMenu" Value="{StaticResource RowMenu}"/>
                </Style>
            </DataGrid.RowStyle>
        </DataGrid>
    </Grid>
    
    0 讨论(0)
  • 2021-01-15 06:26

    These resources will help you on the way:

    • Context Menus in WPF
    • WPF Context Menus
    • How to create Custom WPF Context Menus

    WPF used XAML which is another Markup Language and one common thing that you usualy see is that tags are reused on a lot of controls. In the examples above you can see that controls like

    • RichTextBox
    • Data Grid
    • And many more..

    Has the Control.ContextMenuwhere you can creat your specific menu for that item. Taken from the first link above, see this example on RichTextBox

    <RichTextBox>
        <RichTextBox.ContextMenu>
            <ContextMenu>
            </ContextMenu>
        </RichTextBox.ContextMenu> 
    </RichTextBox>
    

    And this doesn't apply only to the ContextMenu! There are other reusable elements like this. Depending on what DataGrid you are using, you have to look into the API for that but it is most likely working its ways like this.

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