2013-03-22 31 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> 

似乎是爲我工作。 我在這個例子中硬編碼了匹配子字符串的顏色,但是如果你想從標記中傳遞它,你可以添加一個單獨的屬性。

希望這有助於...