我想要一个包含Inline
标记的字符串,如
var str = "foo bar <Bold>dong</Bold>"
并将其提供给TextBlock,这样文本就可以像添加到Inlines集合一样进行格式化。我怎么能做到呢?
您可以用<TextBlock>
标记包装文本,并将整个内容解析为XAML:
public TextBlock CreateTextBlock(string inlines)
{
var xaml = "<TextBlock xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">"
+ inlines + "</TextBlock>";
return XamlReader.Parse(xaml) as TextBlock;
}
然后根据需要使用新创建的TextBlock。把它放在一些面板中
var str = "foo bar <Bold>dong</Bold>";
grid.Children.Add(CreateTextBlock(str));
或者可能将其CCD_ 3复制到另一个TextBlock。
您可以尝试以下代码。
<TextBlock x:Name="txtBlock"/>
string regexStr = @"<S>(?<Str>.*?)</S>|<B>(?<Bold>.*?)</B>";
var str = "<S>foo bar </S><B>dong</B>";
Regex regx = new Regex(regexStr);
Match match = regx.Match(str);
Run inline = null;
while (match.Success)
{
if (!string.IsNullOrEmpty(match.Groups["Str"].Value))
{
inline = new Run(match.Groups["Str"].Value);
txtBlock.Inlines.Add(inline);
}
else if (!string.IsNullOrEmpty(match.Groups["Bold"].Value))
{
inline = new Run(match.Groups["Bold"].Value);
inline.FontWeight = FontWeights.Bold;
txtBlock.Inlines.Add(inline);
}
match = match.NextMatch();
}