我有一个列表视图绑定客户信息。另外,我有一个文本框,在列表视图中提供搜索。如果文本框的键入字符或符号与datalist项匹配,则它会突出显示匹配的项。关于这一点,我想计算匹配的项目编号。但是每次搜索都是“0”。当我调试它时,在foreach循环中计数为真,但在TxtSearch_PreviewKeyDown中它总是为零。请看一看。我怎样才能找到匹配的项目金额?
private int highlightcount;
public int highlightCount
{
get;
set;
}
private void FindListViewItem(DependencyObject obj)
{
try
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
ListViewItem lv = obj as ListViewItem;
if (lv != null)
{
HighlightText(lv);
}
else
FindListViewItem(VisualTreeHelper.GetChild(obj as DependencyObject, i));
}
}
catch
{
MessageBox.Show("Bevor Sie die Suche Stauten, wählen Sie bitte eine Adresse in der linken Spalte aus.");
}
}
/// <summary>
/// Method for highlighting matched listview item
/// </summary>
/// <param name="itx"></param>
public void HighlightText(Object itx)
{
try
{
if (itx != null)
{
if (itx is TextBlock)
{
Regex regex = new Regex("(" + TxtSearch.Text + ")", RegexOptions.IgnoreCase);
TextBlock tb = itx as TextBlock;
if (TxtSearch.Text.Length == 0)
{
string str = tb.Text;
tb.Inlines.Clear();
tb.Inlines.Add(str);
return;
}
string[] substrings = regex.Split(tb.Text);
tb.Inlines.Clear();
highlightCount = 0;
foreach (var item in substrings)
{
if (regex.Match(item).Success)
{
Run runx = new Run(item);
runx.Background = Brushes.Lime;
tb.Inlines.Add(runx);
highlightCount++;
if (tb.IsMouseOver)
{
tb.IsEnabled = false;
}
}
else
{
tb.Inlines.Add(item);
tb.IsEnabled = false;
}
}
return ;
}
else
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(itx as DependencyObject); i++)
{
HighlightText(VisualTreeHelper.GetChild(itx as DependencyObject, i));
}
}
}
}
catch
{
MessageBox.Show("Suche Error");
}
}
private void TxtSearch_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (TxtSearch.Text.Length > 1 && e.Key==Key.Enter)
{
Mouse.OverrideCursor = Cursors.Wait;
ListControl lc = getactivListview();
FindListViewItem(lc);
Mouse.OverrideCursor = null;
MessageBox.Show(highlightCount.ToString());
FocusManager.SetFocusedElement(this, TxtSearch);
}
答案 0 :(得分:0)
尝试从HighlightText方法中删除highlightCount = 0;
,然后将其添加到TxtSearch_PreviewKeyDown
事件处理程序(ListControl lc = getactivListview();
或MessageBox.Show(highlightCount.ToString());
下)