Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / XAML

Text Binding to WinRT RichTextBlock

4.75/5 (4 votes)
1 May 2013CPOL 22.1K   296  
The tip gives an easy way to bind string values to WinRT RichTextBlock

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.

C#
public static string GetText(DependencyObject obj)
{
     return (string)obj.GetValue(TextProperty);
}

public static void SetText(DependencyObject obj, string value)
{
     obj.SetValue(TextProperty, value);
}

// Using a DependencyProperty as the backing store for Text.  
// This enables animation, styling, binding, etc.
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:

XML
<RichTextBlock common1:BindingHelper.Text="{Binding ElementName=calendar, Path=SelectedDate}"/>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)