En fait j'ai une solution un peu mieux (comprendre : plus flexible), à base de propriété attachée :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public static class TextBlockBehavior
{
public static string GetRichText(TextBlock textBlock)
{
return (string)textBlock.GetValue(RichTextProperty);
}
public static void SetRichText(TextBlock textBlock, string value)
{
textBlock.SetValue(RichTextProperty, value);
}
public static readonly DependencyProperty RichTextProperty =
DependencyProperty.RegisterAttached(
"RichText",
typeof(string),
typeof(TextBlockBehavior),
new UIPropertyMetadata(
null,
RichTextChanged));
private static void RichTextChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
TextBlock textBlock = o as TextBlock;
if (textBlock == null)
return;
var newValue = (string)e.NewValue;
textBlock.Inlines.Clear();
if (newValue != null)
AddRichText(textBlock, newValue);
}
private static void AddRichText(TextBlock textBlock, string richText)
{
string xaml = string.Format(@"<Span xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">{0}</Span>", richText);
var content = (Inline)XamlReader.Parse(xaml);
textBlock.Inlines.Add(content);
}
} |
<TextBlock bhv:TextBlockBehavior.RichText="{x:Static prop:Resources.LeTexteRicheEnXaml}" />
Et dans les ressources tu mets une valeur du genre "Hello <Bold>World</Bold>!"
Partager