Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind the text of RichTextBox from Xaml

How to Bind the text of RichTextArea from xaml

like image 965
user281947 Avatar asked Mar 02 '10 06:03

user281947


2 Answers

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>
like image 176
m1m1k Avatar answered Sep 27 '22 21:09

m1m1k


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

        }
    }
}
like image 31
e-rock Avatar answered Sep 27 '22 21:09

e-rock