所以我有一些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
为我做这个。
答案 0 :(得分: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);
}
}
答案 1 :(得分:1)
解决方案
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);