【问题标题】:(WPF DataGrid) How to copy Datagrid header text with a context menu?(WPF DataGrid)如何使用上下文菜单复制 Datagrid 标题文本?
【发布时间】:2015-01-29 07:25:43
【问题描述】:

我正在使用 WPF 数据网格。

我在列标题中添加了一个上下文菜单,但我不知道如何在菜单项单击事件中复制标题文本。

我尝试使用 DataGrid.CurrentColumn 但它为空

非常感谢!

【问题讨论】:

  • 您需要复制所选列及其标题?
  • 我只想复制标题文本。

标签: wpf datagrid columnheader


【解决方案1】:

尝试通过使用选定的单元格获取列标题:

foreach (var item in e.SelectedCells)
{
    DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(item.Item);
    var col = item.Column as DataGridColumn;
    MessageBox.Show("" + col.Header);
}

编辑 如果要获取当前所在的列标题,请添加以下代码:

在资源中放这个:

<ContextMenu x:Key="cm">
            <MenuItem Header="Click"
                                  Click="mi_Click" 
                                  CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Parent}" />
        </ContextMenu>

然后像这样添加列标题样式:

<Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="ContextMenu" Value="{StaticResource cm}"></Setter>
</Style>

然后像这样把代码放在后面:

private void mi_Click(object sender, RoutedEventArgs e)
{
    MenuItem mi = sender as MenuItem;
    if (mi != null)
    {
        ContextMenu cm = mi.CommandParameter as ContextMenu;
        if (cm != null)
        {
            var ch = cm.PlacementTarget as System.Windows.Controls.Primitives.DataGridColumnHeader;
            if (ch != null)
            {
                MessageBox.Show(ch.Content.ToString());
            }
        }
    }
}

【讨论】:

  • 它显示列标题对应于我选择的单元格,但不是我右键单击鼠标所在的列
猜你喜欢
  • 1970-01-01
  • 2014-07-20
  • 2016-05-30
  • 1970-01-01
  • 2014-10-27
  • 2013-12-03
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
相关资源
最近更新 更多