在 TextBlock 中将文本的一部分设置为粗体



我知道我们可以在 XAML 中使用 <Run> 来实现我的要求:

<TextBlock.Inlines>
    <Run Text="This is" />
    <Run FontWeight="Bold" Text="Bold Text." />
</TextBlock.Inlines>

我也可以在代码隐藏中执行此操作,如下所示:

TextBlock.Inlines.Add(new Run("This is"));
TextBlock.Inlines.Add(new Bold(new Run("Bold Text.")));

但我的问题是不同的:

假设我的数据库中有以下文本:

This is <b>Bold Text</b>.

现在,我的文本块绑定到数据库中包含上述文本的字段。

我想要text between <b> and </b> to be bold.我怎样才能做到这一点?

如果要

显示 HTML,请使用 Web 浏览器控件。

<WebBrowser Name="myWebBrowser"/>

在你的代码中,像这样传递你的文本:

myWebBrowser.NavigateToString(myHTMLString);

如果没有,并且粗体是唯一要做的事情,不能嵌套,你可以这样做:

string s = "<b>This</b> is <b>bold</b> text <b>bold</b> again."; // Sample text
var parts = s.Split(new []{"<b>", "</b>"}, StringSplitOptions.None);
bool isbold = false; // Start in normal mode
foreach (var part in parts)
{
     if (isbold)
        myTextBlock.Inlines.Add(new Bold(new Run(part)));
     else
        myTextBlock.Inlines.Add(new Run(part));
     isbold = !isbold; // toggle between bold and not bold
}
看起来

您希望将自定义格式替换为<Bold> - 有关详细信息,请参阅 TextBlock。文章示例:

<TextBlock Name="textBlock1" TextWrapping="Wrap">
  <Bold>TextBlock</Bold> is designed to be <Italic>lightweight</Italic>,
  and is geared specifically at integrating <Italic>small</Italic> portions
  of flow content into a UI.
</TextBlock>

一种方法是重新格式化字符串以匹配TextBlock期望的内容。

如果您有 HTML 输入 - 首先使用 HtmlAgilityPack 解析文本,然后遍历生成的元素并构造字符串,并将b元素替换为<Bold>换行的文本并类似于其他格式。

如果已知数据库内容只有有效的开始/结束对(不是随机 HTML),您甚至可以逃脱基本String.Replace:text = text。替换( ", ")'。

如果您有自己的自定义格式(如*boldtext*),则需要为此发明自定义解析器。

您可以订阅TargetUpdated活动:

 void textBlock_TargetUpdated(object sender, DataTransferEventArgs e)
 {
        string text = textBlock.Text;
        if (text.Contains("<b>"))
        {
            textBlock.Text = "";
            int startIndex = text.IndexOf("<b>");
            int endIndex = text.IndexOf("</b>");
            textBlock.Inlines.Add(new Run(text.Substring(0, startIndex)));
            textBlock.Inlines.Add(new Bold(new Run(text.Substring(startIndex + 3, endIndex - (startIndex + 3)))));
            textBlock.Inlines.Add(new Run(text.Substring(endIndex + 4)));
        }
    }

和 XAML 的TextBlock

<TextBlock x:Name="textBlock" Text="{Binding NotifyOnTargetUpdated=True}"></TextBlock>

相关内容

最新更新