Search code examples
wpfrichtextboxflowdocument

User control with richTextBox, bindable richTextBox


I try make user control with richTextBox because I need bindable richTextbox.

I found some solution here: Richtextbox wpf binding.

I would like to use solution of Arcturus. Create user control with richTextBox control and use dependency property.

In XAML I have only richTextBox control:

<UserControl x:Class="WpfApplication2.BindableRichTextBoxControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <RichTextBox Name="RichTextBox" Grid.Row="0"/>    
    </Grid>
</UserControl>

In CodeBehind:

public partial class BindableRichTextBoxControl : UserControl
{
    public static readonly DependencyProperty DocumentProperty =
    DependencyProperty.Register("Document", typeof(FlowDocument), typeof(BindableRichTextBoxControl), 
    new PropertyMetadata(OnDocumentChanged));

    public FlowDocument Document
    {
        get { return (FlowDocument)GetValue(DocumentProperty); }
        set { SetValue(DocumentProperty, value); }
    }

    private static void OnDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = (BindableRichTextBoxControl)d;
        if (e.NewValue == null)
            control.RichTextBox.Document=new FlowDocument();

        //?
        control.RichTextBox.Document = document;
    }


    public BindableRichTextBoxControl()
    {
        InitializeComponent();
    }
}

I am little confuse with last line in OnDocumentChanged method.

        control.RichTextBox.Document = document;

I can’t identify what is varibale document.


Solution

  • I think he means this:

    private static void OnDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        RichTextBoxControl control = (RichTextBoxControl) d;
        if (e.NewValue == null)
            control.RTB.Document = new FlowDocument(); //Document is not amused by null :)
        else
            control.RTB.Document = e.NewValue;
    }
    

    but I recommend you leave a comment on his original answer.