加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – WPF工具包DataGrid SelectionChanged获取单元格值

发布时间:2020-12-15 20:50:53 所属栏目:百科 来源:网络整理
导读:请帮助我,我试图从SelectionChangedEvent中的选定行获取Cell [0]的值. 我只是设法得到许多不同的Microsoft.Windows.Controls,我希望我错过了一些愚蠢的东西. 希望我能从这里得到一些帮助…… private void datagrid_SelectionChanged(object sender,Selectio
请帮助我,我试图从SelectionChangedEvent中的选定行获取Cell [0]的值.

我只是设法得到许多不同的Microsoft.Windows.Controls,我希望我错过了一些愚蠢的东西.

希望我能从这里得到一些帮助……

private void datagrid_SelectionChanged(object sender,SelectionChangedEventArgs e)
    {
        Microsoft.Windows.Controls.DataGrid _DataGrid = sender as Microsoft.Windows.Controls.DataGrid;
    }

我希望它会像……

_DataGrid.SelectedCells[0].Value;

但是.Value不是一个选择….

非常感谢这一直让我发疯!

解决方法

请检查以下代码是否适合您:

private void dataGrid_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    if (e.AddedItems!=null && e.AddedItems.Count>0)
    {
        // find row for the first selected item
        DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(e.AddedItems[0]);
        if (row != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
            // find grid cell object for the cell with index 0
            DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(0) as DataGridCell;
            if (cell != null)
            {
                Console.WriteLine(((TextBlock)cell.Content).Text);
            }
        }
    }
}

static T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent,i);
        child = v as T;
        if (child == null) child = GetVisualChild<T>(v);
        if (child != null) break;
    }
    return child;
}

希望这有帮助,问候

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读