using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
namespace Developpez.Dotnet.Windows.Behaviors
{
///
/// Fournit des propriétés attachées pour ajouter des fonctionnalités à un TextBlock
///
public static class TextBlockBehavior
{
///
/// Obtient la valeur de la propriété attachée RichText pour l'objet spécifié
///
/// Le TextBlock pour lequel on veut obtenir la valeur de la propriété
/// Le texte riche affiché dans le TextBlock spécifié
[AttachedPropertyBrowsableForType(typeof(TextBlock))]
public static string GetRichText(TextBlock textBlock)
{
return (string)textBlock.GetValue(RichTextProperty);
}
///
/// Définit la valeur de la propriété attachée RichText pour l'objet spécifié
///
/// Le TextBlock pour lequel on veut définir la valeur de la propriété
/// Le texte riche à afficher dans le TextBlock spécifié
public static void SetRichText(TextBlock textBlock, string value)
{
textBlock.SetValue(RichTextProperty, value);
}
///
/// Identifiant de la propriété RichText
///
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(@"{0}", richText);
ParserContext context = new ParserContext();
context.XmlnsDictionary.Add(string.Empty, "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
var bytes = Encoding.UTF8.GetBytes(xaml);
using (var stream = new MemoryStream(bytes))
{
var content = (Span)XamlReader.Load(stream, context);
textBlock.Inlines.Add(content);
}
}
}
}