c# - WPF:将 TextBlock 的绑定(bind)值的一部分加粗

标签 c# .net wpf data-binding

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

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

我环顾四周,但并没有变得更加明智。我想我需要转换器和使用 Inlines(我以前从未使用过)和/或 InlineExpressions(或者那些仅适用于 ASP?)的某种组合。

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

谢谢!

最佳答案

是的,您关于使用转换器(实际上它甚至可能是多转换器)和 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(...) {...}
    }

关于c# - WPF:将 TextBlock 的绑定(bind)值的一部分加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17131182/

相关文章:

c# - 角度theta计算错误

c# - 如何在 C# 中以逗号和换行符拆分字符串?

.net - 如何以编程方式检查 .NET 4.7 Target Pack 是否已安装?

.net - F# null 测试未能检测到 null 值

c# - WPF 中的源绑定(bind),如 Asp.Net

wpf - 在拖放过程中获取鼠标位置

c# - 在生成传出 URL 时针对其他 Controller 中的相同操作方法

c# - 调试实时 ASP.net 网站

c# - 为 TreeView 和 TreeViewItem 触发的 ContextMenuOpening 事件

c# - 在 ASP.Net MVC 中使用硬编码形式将数据插入对象中