using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Media; using MahTweets.Mobile.Core.Extensions; namespace MahTweets.Mobile.Controls { public class HighlightingTextBlock : ContentControl { public static readonly DependencyProperty HighlightBrushProperty = DependencyProperty.Register( "HighlightBrush", typeof (Brush), typeof (HighlightingTextBlock), new PropertyMetadata(null, null)); public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string), typeof ( HighlightingTextBlock), new PropertyMetadata( OnTextPropertyChanged)); public static readonly DependencyProperty ContactNameProperty = DependencyProperty.Register("ContactName", typeof(string), typeof( HighlightingTextBlock), new PropertyMetadata( OnTextPropertyChanged)); public HighlightingTextBlock() { DefaultStyleKey = typeof (HighlightingTextBlock); TextBlock = new TextBlock {TextWrapping = TextWrapping.Wrap}; //Wrap textblock in a border so this control respects background colour var border = new Border { Child = TextBlock, Padding = new Thickness(5,0,5,0) }; border.SetBinding(Border.BackgroundProperty, new Binding("Background") {Source = this}); Content = border; } public Brush HighlightBrush { get { return GetValue(HighlightBrushProperty) as Brush; } set { SetValue(HighlightBrushProperty, value); } } public string Text { get { return GetValue(TextProperty) as string; } set { SetValue(TextProperty, value); } } public string ContactName { get { return GetValue(ContactNameProperty) as string; } set { SetValue(ContactNameProperty, value); } } private TextBlock TextBlock { get; set; } private List Inlines { get; set; } private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var source = (HighlightingTextBlock)d; if (source.TextBlock == null) return; while (source.TextBlock.Inlines.Count > 0) { source.TextBlock.Inlines.RemoveAt(0); } source.TextBlock.Text = String.Empty; var value = e.NewValue as string; source.Inlines = new List(); if (!String.IsNullOrEmpty(source.ContactName)) { Inline run = new Run { Text = source.ContactName + " ", Foreground = source.HighlightBrush, FontWeight = FontWeights.Bold }; source.TextBlock.Inlines.Add(run); source.Inlines.Add(run); } if (value != null) { string[] words = value.Split(' '); foreach (string word in words) { Inline run = new Run {Text = word + " "}; if (word.ContainsHyperlink()) { run.Foreground = source.HighlightBrush; } else if ((word.StartsWith("@") || word.StartsWith(".@") || word.StartsWith("-@") || word.StartsWith("r@") || word.StartsWith("rt@")) && word != "@") { run.Foreground = source.HighlightBrush; } else if (word.StartsWith("#") && word != "#") { run.Foreground = source.HighlightBrush; } source.TextBlock.Inlines.Add(run); source.Inlines.Add(run); } } } } }