WPF:粗体化TextBlock的绑定值的一部分

时间:2013-06-16 07:41:24

标签: c# .net wpf data-binding

我正在寻找一种方法来突出我的自定义ListView控件中的一些搜索词。我有一堆TextBlocks(每行一个属性)。例如,每首歌的艺术家姓名,标题和流派。

现在,如果有人搜索“Emi”,那么我希望艺术家字段显示为<b>Emi</b>nem,如果绑定的值是Eminem。

我已经环顾四周,但并没有更明智。我想我需要一些转换器的组合和使用Inlines(我之前从未使用过)和/或InlineExpressions(或者仅适用于ASP?)。

所有绑定和模板都是在C#中即时创建的,而不是XAML。

谢谢!

1 个答案:

答案 0 :(得分:2)

是的,你是正确的使用转换器(实际上它甚至可能是多通道)和Inline集合的TextBlock。 因此,假设您将搜索项(在您的案例中为'Emi')传递给转换器。您还需要以某种方式操作带有结果文本的TextBlock。为简单起见,我们假设TextBlock的Tag属性(不是Text)包含被搜索的整个字符串(单词'Eminem')。

    class HighlightPartOfTextConverter : IValueConverter {
    public object Convert(object value/*this is TextBlock*/, Type type, object parameter/*this is 'Emi'*/, CultureInfo ci){
        var textBlock = value as TextBlock; 
        string str = textBlock.Tag as string;
        string searchThis = parameter as string;
        int index = str.IndexOf(searchThis);
        if(index >= 0){
            string before = str.Substring(0, index);
            string after = str.Substring(index + searchThis.Length);
            textBlock.Inlines.Clear();
            textBlock.Inlines.Add(new Run(){Text=before});
            textBlock.Inlines.Add(new Run(){Text=searchThis, FontWeight = FontWeights.Bold});
            textBlock.Inlines.Add(new Run(){Text=after});
        }
        return "";
       }

      public object ConvertBack(...) {...}
    }
相关问题