Magic Bullet Dave
Magic Bullet Dave

Reputation: 9076

Binding to RichTextBox Blocks property

I would like to bind directly to the Blocks property of a RichTextBox in my Xaml. This is not possible as the Blocks property is read only. I can bind directly to an individual run:

<RichTextBox x:Name="MyRichTextBox" FontSize="36" Margin="10" Foreground="White">
    <Paragraph>
        <Run Text="{Binding MyObject.Text}" Foreground="Yellow"/>
        <Run Text="{Binding MyObject.Text}" Foreground="Cyan"/>
    </Paragraph>
</RichTextBox>

I would like to do something like:

<RichTextBox x:Name="MyRichTextBox" Blocks="{Binding MyObject.RichTextBlocks}" FontSize="36" Margin="10" Foreground="White"/>

Particularly as I don't know in advance how many blocks will be returned from the binding object.

Is the correct way to achieve this to create an Attached Behaviour for the RichTextBox with a RichTextBlocks property that when being set enumerates through the blocks and calls RichTextBox.Blocks.Add() for each one?

I am new to C#, .NET and XAML so please excuse the elementary question and a simply explained answer would be greatly appreciated.

Upvotes: 1

Views: 2136

Answers (1)

Magic Bullet Dave
Magic Bullet Dave

Reputation: 9076

With the pointers from @Nogard and the other post, I created my own class with a Dependency Property called RichText. Have posted here in case it is of use to anyone else.

  public class MyRichTextBox : RichTextBox
    {
        public static readonly DependencyProperty RichTextProperty = DependencyProperty.Register("RichText", typeof(Paragraph), typeof(MyRichTextBox), new PropertyMetadata(null, RichTextPropertyChanged));

        public Paragraph RichText
        {
            get 
            { 
                return (Paragraph)GetValue(RichTextProperty); 
            }

            set 
            { 
                SetValue(RichTextProperty, value); 
            }
        }

        private static void RichTextPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            MyRichTextBox richTextBox = (MyRichTextBox)dependencyObject;
            Paragraph paragraph = (Paragraph)dependencyPropertyChangedEventArgs.NewValue;

            // Remove any existing content from the text box
            richTextBox.Blocks.Clear();

            // Add the paragraph to the text box
            richTextBox.Blocks.Add(paragraph);
        }
    }
}

and added this to my xaml...

<sub:MyRichTextBox x:Name="MyRichTextOverlay" RichText="{Binding CurrentOverlay.RichTextParagraph}"  VerticalAlignment="Top" FontSize="36" Margin="10" Foreground="White" HorizontalAlignment="Center" TextWrapping="Wrap" TextAlignment="Center"/>

Upvotes: 2

Related Questions