When I created the MyTwich app I asked myself:
How to convert a string into a text and/or image stream while maintaining Binding mechanics?
To do that, you need to create a 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;
}
}
And this is how we use it in XAML.
<RichTextBlock TextWrapping="WrapWholeWords"
myTwitch:BindingTextFormarterHelper.Text="{Binding Message}" />
Here is how the chat looks with emoji:
Original illustration unavailable: Player interface with the chat underneath