【发布时间】:2019-09-24 16:48:46
【问题描述】:
我有两个数据网格。 DG1 和 DG2 具有一列 A(每个)和多行。任务是当用户在另一个数据网格中选择具有相同值的行时,突出显示一个数据网格中的特定行。示例:用户选择 DG1 第 5 行,A 列,其值为“ABC”。 'ABC' 是 DG2 中的第 23 行 A 列。因此 DG 的第 23 行应以“红色”突出显示。 反之亦然(单击 DG2 的第 23 行应突出显示 DG1 的第 5 行)。 目前我的代码通过调用 Datagrid 的 SelectedItem 属性来工作。不利的一面是存在无限循环选择,即当用户选择 DG1 的第 5 行时,它选择 DG2 的第 23 行,然后选择 DG1 的第 5 行,然后选择 DG2 的第 23 行。 因此,我的问题的解决方案可以是解决这个无限循环问题,也可以提供一种方法来突出显示具有特定颜色的数据网格的特定行,从而完全消除对数据网格的 selecteditem 属性的调用。
这里有一些代码:
//This is the function invoked when a user selects a row in a DG1
private void DG1SelectedItem(object sender, SelectionChangedEventArgs e)
{
if (DG1.SelectedItem != null)
{
var val = DG1.SelectedItem; //Get the paticular row that was selected
DataRowView row = (DataRowView)val;
object[] list = row.Row.ItemArray;
String rowValue = list[0].ToString(); //get the value within that selected row
HighLightRow(DG2, account); //Call a function that highlights a particular row in a Datagrid with a given string value
}
}
//This is the function invoked when a user selects a row in a DG2
private void DG2SelectedItem(object sender, SelectionChangedEventArgs e)
{
if (DG2.SelectedItem != null)
{
var val = DG2.SelectedItem; //Get the paticular row that was selected
DataRowView row = (DataRowView)val;
object[] list = row.Row.ItemArray;
String rowValue = list[0].ToString(); //get the value within that selected row
HighLightRow(DG1, account); //Call a function that highlights a particular row in a Datagrid with a given string value
}
}
//Function to highlight the row in datagrid 'dg' with value of 'value' (only checks first column)
private void HighLightRow(DataGrid dg, string value)
{
dg.UnselectAll();
var itemsource = dg.ItemsSource as IEnumerable;
int index = 0;
ArrayList rowIndices = new ArrayList();
//loop through entire datagrid looking for the string 'value' in the first column
//if found, store the index in an array so it can be utillized to highlight all rows later on
foreach (var item in itemsource)
{
DataRowView row = item as DataRowView;
object[] list = row.Row.ItemArray;
String valueToFind = list[0].ToString();
if (valueToFind.Equals(value))
rowIndices.Add(index);
index++;
}
//For all rows where the string 'value' was foung in the first column of the datagrid, highlight it
//Currently the implementation relies on SelectedItem
for (int i = 0; i < rowIndices.Count; i++)
{
object item = dg.Items[(int)rowIndices[i]];
dg.SelectedItem = item; //this code then invokes DG2SelectedItem (or DG1SelectedItem depending on which SelectedItem function was initially invoked) and we have the inifite loop problem
**/*
This is where I would like to select the row at the indices stored in rowIndices and highlight them red (and not rely on dg.SelectedItem like in the line above)
Something like:
dg.Row[i].Background = Brushes.Red;
*/**
int m = dg.SelectedIndex;
dg.UpdateLayout();
dg.ScrollIntoView(dg.Items[m]);
}
dg.LoadingRow += Dg_LoadingRow;
}
【问题讨论】:
标签: c# wpf datagrid selecteditem