EditCategory
Data Binding
EditQuestion
How can I databind to the Run element?
EditAnswer
The short answer is: you can't!
The long answer is...
/// <summary>
/// A subclass of the Run element that exposes a DependencyProperty property to allow data binding.
/// </summary>
/// <remarks>
/// See http://fortes.com/2007/03/bindablerun/
/// and http://code.logos.com/blog/2008/01/data_binding_in_a_flowdocument.html
/// </remarks>
public class BindableRun : Run
{
public static readonly DependencyProperty BoundTextProperty
= DependencyProperty.Register("BoundText",
typeof (string),
typeof (BindableRun),
new PropertyMetadata(
new PropertyChangedCallback
(onBoundTextChanged)));
public BindableRun()
{
var b = new Binding("DataContext")
{
RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof (FrameworkElement), 1)
};
SetBinding(DataContextProperty, b);
}
public String BoundText
{
get { return (string) GetValue(BoundTextProperty); }
set { SetValue(BoundTextProperty, value); }
}
private static void onBoundTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((Run) d).Text = (string) e.NewValue;
}
}
Now, where ever you want to bind the text in a Run element, replace it with a BindableRun element...
<UI:BindableRun Typography.Capitals="SmallCaps" BoundText="{Binding Path=Title, Mode=Default}" ></UI:BindableRun>
and, of course, register the namespace prefix you are using in the root element:
... xmlns:UI="clr-namespace:MyNamespace.UI;assembly=MyCoreAssembly" ...
EditKeywords
databinding, binding, run