我正在通过文本框在数据网格中搜索,我的代码突出显示了数据网格单元格中搜索到的文本,并根据搜索过滤了行。这对于少量的行很好用,但是随着行的增加它变得非常慢。有人可以提出任何建议以提高效率,我会很感激:)
突出显示数据网格单元格中的搜索文本
public void HighlightSearch()
{
if (string.IsNullOrEmpty(SearchText))
{
if ((dataGrid.ItemsSource as DataView).RowFilter == "")
return;
}
string searchtext = SearchText;
Regex SearchRegex = new Regex(searchtext, RegexOptions.IgnoreCase);
if (dataGrid.ItemsSource != null)
{
for (int i = 0; i < dataGrid.Columns.Count; i++)
{
var checkbox = SearchColumns[i];
if (checkbox.IsChecked == true)
{
for (int j = 0; j < dataGrid.Items.Count; j++)
{
DataGridCell cell = GetCell(j, i);
string[] substrings =null;
if (cell.Content is TextBlock itx)
{
Regex regex = new Regex("(" + SearchText + ")", RegexOptions.IgnoreCase);
TextBlock tb = itx as TextBlock;
if (SearchText.Length == 0)
{
string str = tb.Text;
tb.Inlines.Clear();
tb.Inlines.Add(str);
}
else
{
substrings = regex.Split(tb.Text);
tb.Inlines.Clear();
foreach (var item in substrings)
{
if (regex.Match(item).Success)
{
Run runx = new Run(item);
runx.Background = Brushes.Blue;
tb.Inlines.Add(runx);
}
else
{
tb.Inlines.Add(item);
}
}
}
}
}
}
}
}
}
过滤行
private void FilterGrid()
{
if (dataGrid.ItemsSource != null)
{
string query = "";
foreach (CheckBox checkbox in SearchColumns)
{
if (checkbox.IsChecked == true)
{
// to check if its the first columns and form the appropriate filter query ;)
if (query == "")
query = $"Convert([{checkbox.Content}], System.String) LIKE '%{SearchText}%'";
else
query += $" or Convert([{checkbox.Content}], System.String) LIKE '%{SearchText}%'";
}
}
(dataGrid.ItemsSource as DataView).RowFilter = query;
}
}
要获取数据网格的每个单元格,我都点击了此链接https://social.msdn.microsoft.com/Forums/vstudio/en-US/9a1872d9-a50b-4bf3-81fc-db0ac4a26d1c/search-in-a-datagridlistview-and-highlight-text?forum=wpf
public DataGridCell GetCell(int row, int column)
{
DataGridRow rowContainer = GetRow(row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
public DataGridRow GetRow(int index)
{
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
dataGrid.UpdateLayout();
dataGrid.ScrollIntoView(dataGrid.Items[index]);
row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
public 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;
}