WPF Datagrid设置所选行 [英] WPF Datagrid set selected row
问题描述
如何使用 Datagrid.SelectedItem
以编程方式选择一行?
How do I use the Datagrid.SelectedItem
to select a row programmatically?
创建一个 IEnumerable
DataGridRow
对象,并将匹配的行传递给此 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.
推荐答案
请检查以下代码是否适合您;它遍历datagris第一列的单元格,并检查单元格内容是否等于textbox.text值并选择该行。
please check if code below would work for you; it iterates through cells of the datagris'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屋!