1

ItemsSource绑定了我的数据。我有一个,当用户开始输入它时,我会根据更改的事件TextBox根据以下内容过滤项目:Filter predicatetextBoxText

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

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

这工作正常并过滤列表。但是,我还希望这些项目在键入时以黄色突出显示输入的搜索条件。我怎样才能在 wpf 中做到这一点?有一些像:

如果我搜索“est”并且该项目是ForestThe Forest 项目est以黄色或任何其他颜色突出显示ListBox?感谢您的任何建议。

4

1 回答 1

1

我通过创建一个自定义控件来实现这一点 -HighlightableTextBlock它继承TextBlock并添加了以下依赖属性:

    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));
            }
        }
    }

事物的标记方面如下所示:

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

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

希望这可以帮助...

于 2016-10-09T22:39:06.327 回答