选择一个包含wpf中给定值的datagrid单元格 [英] select a datagrid cell that contains a given value in wpf
问题描述
我将数据表绑定到wpf中的数据网格。第一列具有唯一值。现在,我想自动选择第二列中第一列具有给定值的单元格。我应该如何实现?例如,这是我的数据网格:
I bound a DataTable to a datagrid in wpf. The first column has unique values. Now I would like to autoselect a cell in the second column whose first column cell has the given value. How should I achieve that? For example,here is my datagrid:
名称|年龄
猫 | 2
狗 | 3
Name | Age
cat | 2
dog | 3
当用户输入 dog时,我需要选择 3。
When user input 'dog', I will need the '3' to be selected.
我尝试了这里显示的方法:
如何在WPF DataGrid中以编程方式选择行或单元格?
但是,我无法弄清楚显示的行号。即使我知道dataTable的行号,但由于允许用户对表进行排序,因此显示号可能会有所不同。
非常感谢。
I tried the method show here:
How to select a row or a cell in WPF DataGrid programmatically?
However, I cannot figure out the displaying row number. Even though I know the row number of the dataTable, the display number can be different since I allow users to sort the table.
Thanks a lot.
推荐答案
将网格的SelectionUnit属性设置为 Cell,并假定使用表的DefaultView馈送DataGrid:
Set your grid's SelectionUnit property to "Cell", and assuming you feed the DataGrid with the table's DefaultView:
private void button1_Click(object sender, RoutedEventArgs e)
{
// Search for the source-row.
var Element = MyDataTable.AsEnumerable()
.FirstOrDefault(x => x.Field<string>("Name") == "horse");
if (Element == null) return;
// Found the row number in the DataGrid
var RowOnGrid = MyGrid.Items.OfType<DataRowView>()
.Select((a, Index) => new { data=a.Row, index = Index })
.Where(x=> x.data == Element)
.Select(x => x.index)
.FirstOrDefault();
// Assuming the desired column is the second one.
MyGrid.SelectedCells.Clear();
MyGrid.SelectedCells.Add(new DataGridCellInfo(MyGrid.Items[RowOnGrid], MyGrid.Columns[1]));
}
即使对行进行重新排序,它也应该起作用。
It should work even if you re-sort the rows.
这篇关于选择一个包含wpf中给定值的datagrid单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!