WPFwiki, wpf, wiki, .net 3.0, windows presentation foundation, FAQ, free resources, solution, development, microsoft Home of the world's largest WPF FAQ
Edit

Category

Data Binding

Edit

Question

How can I databind to the Run element?

Edit

Answer

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" ... 


Edit

Keywords

databinding, binding, run

All content is Copyright ©2007 Xceed Software Inc. unless otherwise indicated. See the Terms of Service. Contributors must read and agree to the Contribution Policy. WPFwiki is brought to you by Xceed, makers of the powerful yet free Xceed DataGrid for WPF.