Ajouter des smiley dans une RichTextBlock
Lorsque j’ai créé l’application MyTwich je me suis posé la question :
Comment convertir un string en flux texte et/ou image, tout en conservant la mechanique de Binding?
Pour ce faire il faut créer un DependencyObject.
public class BindingTextFormarterHelper : DependencyObject { public static string GetText(DependencyObject obj) { return (string)obj.GetValue(TextProperty); } public static void SetText(DependencyObject obj, string value) { obj.SetValue(TextProperty, value); } public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached("Text", typeof(string), typeof(BindingTextFormarterHelper), new PropertyMetadata(String.Empty, OnTextChanged)); private static void OnTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var control = sender as RichTextBlock; if (control != null) { control.Blocks.Clear(); if (e.NewValue != null) { //Quand le texte change on va créer les blocks. string value = e.NewValue.ToString(); control.Blocks.Add(SplitString(value)); } } } static Paragraph SplitString(string message) { var ret = new Paragraph(); //On divise le texte en mots var words = message.Split(' '); Dictionary<string,string> icons = new Dictionary<string,string>(); icons.Add(":)","ImagePath1"); icons.Add(":'(","ImagePath2"); foreach (var word in words) { //Si le mots est un des icons on génère le container adequat. if(icons.ContainsKey(word)) { //On récupère le chemin de le chemin du fichier image var iconPath = icons[word]; var container = new InlineUIContainer(); container.Child = new Image() { Height = 20, Width = 20, VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center, Source = new BitmapImage(new Uri(iconPath)) }; ret.Inlines.Add(container); break; } else ret.Inlines.Add(new Run { Text = word + " " }); } return ret; } }
Et voici comment on l’utilise en XAML.
<RichTextBlock TextWrapping="WrapWholeWords" myTwitch:BindingTextFormarterHelper.Text="{Binding Message}" />
Un exemple de visuel de chat avec des emoticones :