【问题标题】:Make a word in a TextBlock bold使 TextBlock 中的单词变为粗体
【发布时间】:2014-09-04 11:07:05
【问题描述】:

所以我有一些 XAML 可以使某些单词变粗

<TextBlock x:Name="Instructions">
  This text is normal <bold> this text is bold </bold>
</TextBlock>

但是我需要能够通过 C# 来做到这一点,因为我会动态更改指令,例如

String Instruction1 = "Do something to <bold> item x </bold>"
String Instruction2 = "Do something to <bold> item y </bold>"

我知道该字符串不处理任何格式,但我不确定如何操纵 TextBox 为我执行此操作。

【问题讨论】:

  • 使用Inlines,如您上一个问题的答案所示。
  • 这允许我添加一个完全粗体的字符串,而不是由不同样式组成的字符串?
  • 你能把它取消标记为重复吗.. 上一个答案不能解决我的问题。
  • 如果这是关于如何在 Windows 应用商店应用程序中使用内联的问题,则不应将其标记为 WPF。 WPF 不用于 Windows 应用商店应用。
  • Run 类在 Windows 运行时中只有一个默认构造函数。改为设置 Text 属性。并使用Bold 对象开始一个粗体文本部分。

标签: c# xaml windows-8 microsoft-metro


【解决方案1】:

您想使用标记文本。查看这篇文章:

http://www.codeproject.com/Articles/234651/Basic-HTML-Markup-in-WPF-TextBlock

更新

我知道这不是你问的,但也许你会发现它有帮助(代码项目库让我很好奇)。

XElement xmlTree = XElement.Parse("<root><b>Should be bold</b>Shouldn't be bold</root>");
AddRuns(BlockInstructions.Inlines, xmlTree);

void AddRuns(InlineCollection inlines, XNode node, bool isBold = false, bool  isItalic = false)
{   
    var inline = new Run {
        FontWeight = isBold ? FontWeights.Bold : FontWeights.Normal,
        FontStyle = isItalic ? FontStyles.Italic : FontStyles.Normal
    };
    inlines.Add(inline);

    var element = node as XElement;
    if (null != element)
    {
        foreach (var item in element.Nodes())
        {
            AddRuns(
                inline.SiblingInlines,
                item,
                element.Name.LocalName == "b" || isBold,
                element.Name.LocalName == "i" || isItalic
            );
        }
    }
    else
    {
        inline.Text = Convert.ToString(node);
    }
}

【讨论】:

    【解决方案2】:

    解决方案

    Run bold = new Run();
    bold.Text = "Should be bold";
    
    bold.FontWeight = FontWeights.Bold;
    
    BlockInstructions.Inlines.Add(bold);
    
    
    
    Run notbold = new Run();
    notbold.Text = "Shouldn't be bold";
    
    notbold.FontWeight = FontWeights.Normal;
    
    BlockInstructions.Inlines.Add(notbold);
    

    【讨论】:

      猜你喜欢
      • 2011-07-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 2014-04-29
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多