【问题标题】:Adding different context menu for datagrid's header为数据网格的标题添加不同的上下文菜单
【发布时间】:2011-02-11 23:17:42
【问题描述】:

我想在 WPF 上为我的数据网格标题添加不同的上下文菜单。我该怎么做?

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    您可以分别使用 DataGrid.ColumnHeaderStyle 或 DataGrid.RowStyle 为数据网格列标题或数据网格行创建上下文菜单。见例子:

    <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>
    

    【讨论】:

      【解决方案2】:

      这些资源将为您提供帮助:

      WPF 使用了 XAML,它是另一种标记语言,您通常会看到一个常见的事情是标签在很多控件上被重用。在上面的示例中,您可以看到类似的控件

      具有Control.ContextMenu,您可以在其中为该项目创建特定菜单。取自上面的第一个链接,请参阅RichTextBox上的此示例

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

      这不仅仅适用于ContextMenu!还有其他类似的可重用元素。根据您使用的 DataGrid,您必须为此研究 API,但它很可能是这样工作的。

      【讨论】:

        猜你喜欢
        • 2013-05-11
        • 2011-03-18
        • 1970-01-01
        • 1970-01-01
        • 2011-07-09
        • 2014-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多