Reputation: 1961
I would like to have string containing Inline
markups like
var str = "foo bar <Bold>dong</Bold>"
and feed TextBlock with it so the text would get formatted like it would be added to Inlines collection. How could I achive that?
Upvotes: 1
Views: 1253
Reputation: 128146
You could wrap the text with a <TextBlock>
tag and parse the whole thing as 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;
}
Then use the newly created TextBlock as you like. Put it in some Panel
var str = "foo bar <Bold>dong</Bold>";
grid.Children.Add(CreateTextBlock(str));
or perhaps copy its Inlines
to another TextBlock.
Upvotes: 5
Reputation: 5366
You can try the below code.
<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();
}
Upvotes: -1