Bind the text of RichTextBox from Xaml

前端 未结 6 2033
名媛妹妹
名媛妹妹 2020-12-18 19:19

How to Bind the text of RichTextArea from xaml

6条回答
  •  悲&欢浪女
    2020-12-18 20:01

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

提交回复
热议问题