根据文本框突出显示列表框内的listboxitems文本:

时间:2010-05-20 07:23:26

标签: c# silverlight

我有一个列表框,每当我更新listboxitemsource时,我会根据文本框的文本更改事件在其中显示增量搜索结果。列表框中显示的项目必须突出显示它的文本。

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提前

2 个答案:

答案 0 :(得分:1)

首先:TextBlock可以由一系列Inline项组成,每个项都可以具有不同的字体特征。试着看看结果: -

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

第二次:只要您绑定一次,就可以将ListBox绑定到ObservableCollection<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。

答案 1 :(得分:0)

也许使用RichTextBox而不是ListView? 然后你可以加粗每个字符串匹配。