开发者

Adding different context menu for datagrid's header

开发者 https://www.devze.com 2022-12-28 14:59 出处:网络
I want to add a different context menu for my datagrid\'s header on WPF. How can I do tha开发者_StackOverflow社区t?These resources will help you on the way:

I want to add a different context menu for my datagrid's header on WPF. How can I do tha开发者_StackOverflow社区t?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消