2010-05-20 42 views
1

我有一個列表框,並且基於文本框的文本更改事件顯示增量搜索結果,每次更新listboxitemsource。列表框內顯示的項目必須高亮顯示。根據文本框高亮顯示列表框中的listboxitems文本:

Suppose the person enter in textbox sy and the listbox displays the result all getting started with sy : 
Somewhat like this..., 
System 
SystemDefault 
SystemFolder 

so for the all above 3 results Sy must be highlighted. 

如何實現這一目標? tx

+0

Silverlight 3或4? – AnthonyWJones 2010-05-20 09:38:23

+0

我正在使用Silverlight 4 – Malcolm 2010-05-20 09:55:51

回答

1

第一個:一個TextBlock可以由一系列Inline項目組成,每個項目可以有不同的字體特徵。試着看一下這個結果: -

<TextBlock><Run FontWeight="Bold">Sy</Run><Run>stem</Run></TextBlock> 

:你只能把它綁定,只要綁定ListBoxObservableCollection<TextBlock>你一次。

第三個:您可以操縱代碼中文本塊的集合Inlines的內容。

全部放在一起: -

的XAML: -

<UserControl x:Class="StackoverflowSpikes.ItemHighlighter" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
> 
    <Grid x:Name="LayoutRoot" Background="White"> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="Auto" /> 
      <RowDefinition Height="*" /> 
     </Grid.RowDefinitions> 
     <TextBox Name="textBox1" TextChanged="textBox1_TextChanged" /> 
     <ListBox Grid.Row="1" Name="listBox1" /> 
    </Grid> 
</UserControl> 

代碼: -

using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Collections.ObjectModel; 

namespace StackoverflowSpikes 
{ 
    public partial class ItemHighlighter : UserControl 
    { 
     ObservableCollection<TextBlock> items = new ObservableCollection<TextBlock>(); 
     string[] source = new string[] { "Hello", "World", "System", "SystemDefault", "SystemFolder" }; 

     public ItemHighlighter() 
     { 
      InitializeComponent(); 
      Loaded += new RoutedEventHandler(ItemHighlighter_Loaded); 
     } 

     void ItemHighlighter_Loaded(object sender, RoutedEventArgs e) 
     { 
      foreach (string s in source) 
      { 
       TextBlock item = new TextBlock(); 
       item.Inlines.Add(new Run() { Text = "", FontWeight = FontWeights.Bold }); 
       item.Inlines.Add(new Run() { Text = s }); 
       items.Add(item); 
      } 
      listBox1.ItemsSource = items; 
     } 

     private void textBox1_TextChanged(object sender, TextChangedEventArgs e) 
     { 
      string match = textBox1.Text; 
      foreach (TextBlock item in listBox1.Items) 
      { 
       Run bold = ((Run)item.Inlines[0]); 
       Run normal = ((Run)item.Inlines[1]); 

       string s = bold.Text + normal.Text; 

       if (s.StartsWith(match)) 
       { 

        bold.Text = s.Substring(0, match.Length); 
        normal.Text = s.Substring(match.Length); 
       } 
       else 
       { 
        bold.Text = ""; 
        normal.Text = s; 
       } 
      } 
     } 
    } 
} 

噼進入一個新的項目這一點,有一齣戲。應該工作SL3和4.

+0

tx爲答案,它有助於解決我的問題:)剛剛播放liitle位與給定的邏輯..我會在一段時間後發佈我的答案.. :) – Malcolm 2010-05-20 14:45:40

0

也許使用RichTextBox而不是ListView? 然後你可以加粗每個字符串的匹配。