我想要包含Inline
标记的字符串,如
var str = "foo bar <Bold>dong</Bold>"
并向其提供TextBlock,以便将文本格式化为将其添加到Inlines集合中。我怎么能得到那个?
答案 0 :(得分:4)
您可以使用<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。把它放在一些Panel
中var str = "foo bar <Bold>dong</Bold>";
grid.Children.Add(CreateTextBlock(str));
或者可能将其Inlines
复制到另一个TextBlock。
答案 1 :(得分:0)
您可以尝试以下代码。
<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();
}