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 a Senior Development Engineer in Aditi Technologies,Bangalore, India. Specialist in all XAML frameworks. Very passionate on UX Design and Development. Skilled in Expression Blend, Design, WPF, Silverlight, Windows Phone 7/8, Windows 8. Good knowledge in Entity Framework, SQLite and SQL Server also. Also had good experience with PRISM, MVVM, Caliiburn Micro and other design patterns.
He developed few products for Syncfusion Inc. Also working on some freelancing projects. Worked as a lead developer of Metro Studio from Syncfusion Inc.
An active freelancer. http://xamlfactory.elance.com
http://about.me/jawahars
http://wpfplayground.com/