1. 程式人生 > >wpf 設定文字樣式

wpf 設定文字樣式

使用inline屬性

後臺:

public static string GetInlineText(DependencyObject obj)

{

return (string)obj.GetValue(InlineTextProperty);

}

public static void SetInlineText(DependencyObject obj, string value)

{

obj.SetValue(InlineTextProperty, value);

}

public static readonly DependencyProperty InlineTextProperty = DependencyProperty.RegisterAttached(

"InlineText"

typeof(string), 

typeof(InlineTextBehaviour), 

new PropertyMetadata(null, InlineTextChanged)

);

static void InlineTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)

{

var textBlock = sender as TextBlock;

if (textBlock != null)

{

textBlock.Inlines.Clear();

textBlock.Inlines.Add(FormatText(e.NewValue as string ?? ""));

}

}

static Dictionary<string, Func<string, Run>> keywords = new Dictionary<string, Func<string, Run>>()

{

{"你好", s => new Run(s){Foreground = Brushes.Red}},

{"朋友", s => new Run(s){Foreground = Brushes.Blue, FontSize = 28}},

};

static Inline FormatText(string text)

{

Span span = new Span();

int startIndex = 0;

while (true)

{

var hit = keywords.Keys.Select(k => new { word = k, index = text.IndexOf(k, startIndex) }).OrderBy(x => (uint)x.index).FirstOrDefault();

if(hit.index < 0)

{

span.Inlines.Add(new Run(text.Substring(startIndex)));

break;

}

span.Inlines.Add(new Run(text.Substring(startIndex, hit.index - startIndex)));

span.Inlines.Add(keywords[hit.word](hit.word));

startIndex = hit.index + hit.word.Length;

}

return span;

}

前臺: 

<TextBlock loc:InlineTextBehaviour.InlineText="你好,1111朋友" />