2013-03-22 67 views
1

我有一个ItemsSource绑定到我的数据。我有一个TextBox,随着用户开始打字,我筛选基于以下Filter predicate项目上textBoxText更改事件:筛选wpf时ItemsSource高亮显示?

ICollectionView listView = CollectionViewSource.GetDefaultView(myControl.ItemsSource); 

listView.Filter = ((x) => 
{   
    MyData data = x as MyData; 
    return data.Name.Contains(searchString, System.StringComparison.InvariantCultureIgnoreCase); 
}); 

能正常工作和筛选器列表。不过,我还希望这些项目在输入时以黄色突出显示输入的搜索条件。我怎么能在wpf中做到这一点? 有点像:

如果我搜索“EST”及产品Forest森林项目亮点est黄色或其他颜色的ListBox?感谢您的任何建议。

public string HighlightSource 
    { 
     get { return (string)GetValue(HighlightSourceProperty); } 
     set { SetValue(HighlightSourceProperty, value); } 
    } 

    public static readonly DependencyProperty HighlightSourceProperty = 
     DependencyProperty.Register("HighlightSource", typeof(string), typeof(HighlightableTextBlock), new PropertyMetadata("", OnChange)); 

OnChange事件处理程序执行实际的高亮::

static void OnChange(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     var textBlock = d as HighlightableTextBlock; 
     var text = textBlock.Text; 
     var source = textBlock.HighlightSource; 

     if (!string.IsNullOrWhiteSpace(source) && !string.IsNullOrWhiteSpace(text)) 
     { 
      var index = text.IndexOf(source); 
      if (index >= 0) 
      { 
       var start = text.Substring(0, index); 
       var match = text.Substring(index, source.Length); 
       var end = text.Substring(index + source.Length); 

       textBlock.Inlines.Clear(); 
       textBlock.Inlines.Add(new Run(start)); 
       textBlock.Inlines.Add(new Run(match) { Foreground = Brushes.Red }); 
       textBlock.Inlines.Add(new Run(end)); 
      } 
     } 
    } 

而且HighlightableTextBlockTextBlock继承并增加了以下依赖属性 -

+0

你也许模板项目以'TextBox'并绑定'SelectionStart'和'SelectionLength'属性...我会希望看到一个解决的办法。 – 2013-03-22 20:08:46

+0

可能会查看这些链接http://underground.infovark.com/2011/03/03/highlighting-query-terms-in-a-wpf-textblock/ – isakavis 2013-03-22 20:29:46

回答

0

我通过创建一个自定义的控制来实现这东西的标记面看起来像这样:

<controls:HighlightableTextBlock Text="{Binding SomeText}" 
           HighlightSource="{Binding ElementName=SearchTextBox, Path=Text}"> 
</controls:HighlightableTextBlock> 

似乎是为我工作。 我在这个例子中硬编码了匹配子字符串的颜色,但是如果你想从标记中传递它,你可以添加一个单独的属性。

希望这有助于...