Introduction
Normally, it is not possible to bind text to WinRT RichTextBlock as we do for TextBlock. RichTextBlock is devoid of Text dependency property. So the only way is to populate the Blocks property with paragraphs in code behind. But by simply declaring an attached property, we can achieve binding to text in RichTextBlock.
Using the Code
The callback of attached property will create a new paragraph and add it to blocks of RichTextBlock. The Inlines property of RichTextBlock contains Run objects, whose Text is set to new value of the property.
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(BindingHelper), new PropertyMetadata(String.Empty, OnTextChanged));
private static void OnTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as RichTextBlock;
if (control != null)
{
control.Blocks.Clear();
string value = e.NewValue.ToString();
var paragraph = new Paragraph();
paragraph.Inlines.Add(new Run {Text = value});
control.Blocks.Add(paragraph);
}
}
The XAML side binding will look like below:
<RichTextBlock common1:BindingHelper.Text="{Binding ElementName=calendar, Path=SelectedDate}"/>
Jawahar working as Software Developer in Chennai, developing WPF and Silverlight UI components. He usually strong in Expression Blend, WPF/Silverlight control developement, Data Binding.
Developed few products for Syncfusion Inc.
http://wpfplayground.blogspot.com/