Click here to Skip to main content
Click here to Skip to main content

Text Binding to WinRT RichTextBlock

By , 1 May 2013
 

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);
}

// 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:

<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)

About the Author

Jawahar Suresh Babu
Software Developer
India India
Member
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/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130513.1 | Last Updated 1 May 2013
Article Copyright 2013 by Jawahar Suresh Babu
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid