19

How to Bind the text of RichTextArea from xaml

Todd Main
  • 28,951
  • 11
  • 82
  • 146
user281947
  • 275
  • 1
  • 2
  • 5

5 Answers5

26

They've got the easier answer here:

Silverlight 4 RichTextBox Bind Data using DataContext and it works like a charm.

<RichTextBox>
  <Paragraph>
    <Run Text="{Binding Path=LineFormatted}" />
  </Paragraph>
</RichTextBox>
Community
  • 1
  • 1
m1m1k
  • 1,375
  • 13
  • 14
4

You can use the InlineUIContainer class if you want to bind a XAML control inside of an inline typed control

<RichTextBlock>
<Paragraph>
    <InlineUIContainer>
        <TextBlock Text="{Binding Name"} />
    </InlineUIContainer>
</Paragraph>
</RichTextBlock>
jeuxjeux20
  • 391
  • 1
  • 6
  • 20
Kevin Tan
  • 169
  • 12
4

Here is the solution I came up with. I created a custom RichTextViewer class and inherited from RichTextBox.

using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;

namespace System.Windows.Controls
{
    public class RichTextViewer : RichTextBox
    {
        public const string RichTextPropertyName = "RichText";

        public static readonly DependencyProperty RichTextProperty =
            DependencyProperty.Register(RichTextPropertyName,
                                        typeof (string),
                                        typeof (RichTextBox),
                                        new PropertyMetadata(
                                            new PropertyChangedCallback
                                                (RichTextPropertyChanged)));

        public RichTextViewer()
        {
            IsReadOnly = true;
            Background = new SolidColorBrush {Opacity = 0};
            BorderThickness = new Thickness(0);
        }

        public string RichText
        {
            get { return (string) GetValue(RichTextProperty); }
            set { SetValue(RichTextProperty, value); }
        }

        private static void RichTextPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            ((RichTextBox) dependencyObject).Blocks.Add(
                XamlReader.Load((string) dependencyPropertyChangedEventArgs.NewValue) as Paragraph);

        }
    }
}
e-rock
  • 141
  • 1
  • 8
3

There is no built in way to do that. You can create Text attached property and bind to it like discussed here

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
0

This can't be done, you have to manually update it. Document is not a DependencyProperty.

Ana Betts
  • 73,868
  • 16
  • 141
  • 209