WPF Datagrid 设置选定行 [英] WPF Datagrid set selected row

查看:82
本文介绍了WPF Datagrid 设置选定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Datagrid.SelectedItem 以编程方式选择一行?

How do I use the Datagrid.SelectedItem to select a row programmatically?

我是否首先必须创建 DataGridRow 对象的 IEnumerable 并将匹配的行传递给这个 SelectedItem 属性,或者我该怎么做?

Do I first have to create a IEnumerable of DataGridRow objects and pass the matching row to this SelectedItem property or how do I do it?

在选择行之前,我需要首先将第一列单元格的单元格内容与 TextBox.Text 匹配.

I need to match the cell content of the first columns cell with a TextBox.Text first, before selecting the row.

推荐答案

我的代码遍历 datagrid 第一列的单元格并检查单元格内容是否等于 textbox.text 值并选择行.

My code iterates through cells of the datagrid's first column and checks if cell content equals to the textbox.text value and selects the row.

for (int i = 0; i < dataGrid.Items.Count; i++)
{
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
    TextBlock cellContent = dataGrid.Columns[0].GetCellContent(row) as TextBlock;
    if (cellContent != null && cellContent.Text.Equals(textBox1.Text))
    {
        object item = dataGrid.Items[i];
        dataGrid.SelectedItem = item;
        dataGrid.ScrollIntoView(item);
        row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        break;
    }
}

这篇关于WPF Datagrid 设置选定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆