Home > front end >  Why doesn't my RichTextBox change the text when I type it?
Why doesn't my RichTextBox change the text when I type it?

Time:06-22

I have a RichTextbox and now I am typing some text. The text is also changed in the view, but if I now want to get to the text in the code behind, it always gives me the placeholder text and not the one I entered.

Which means that first look(PlaceHolder):

Placeholder

Code from The RichTextBox:

<Grid Grid.Row="2">


                    <RichTextBox x:Name="rtb1" IsHitTestVisible="True" HorizontalAlignment="Right" 
                     TextChanged="OnDocumentChanged" BorderThickness="0" FontSize="40"
                     Background="Transparent" Panel.ZIndex="2">
                      
                        <FlowDocument TextAlignment="Center" >
                            <Paragraph >
                                <Run Text="Hallo" />
                            </Paragraph>
                    </FlowDocument>
                </RichTextBox>
                    <TextBox x:Name="tb1" Style="{StaticResource tb1}" Text="Eingabe" FontSize="40" TextWrapping="Wrap" Panel.ZIndex="1" TextAlignment="Center" Foreground="DarkGray">
                       
                    </TextBox>
                  
                </Grid>

Then my change in the View:

ViewChange

And then I try to get the Text From Code behind:

        string richText = new TextRange(rtb1.Document.ContentStart, rtb1.Document.ContentEnd).Text;
        MessageBox.Show(richText);

But the Output is this:

Output

How Can I get that what I have written in Code Behind?

CodePudding user response:

I adjusted your script a bit by removing the <FlowDocument/> and replacing it with manual Width and Height.

Try this:

 <Grid Grid.Row="2">
        <RichTextBox x:Name="rtb1" IsHitTestVisible="True" HorizontalAlignment="Center" 
                     TextChanged="rtb1_TextChanged" BorderThickness="0" FontSize="40"
                     Background="Transparent" Panel.ZIndex="2" Width="400" Height="100" 
                     VerticalAlignment="Top" Cursor="Arrow"/>
        <TextBox x:Name="tb1" Text="Eingabe" FontSize="40" TextWrapping="Wrap" 
                 Panel.ZIndex="1" TextAlignment="Center" Foreground="DarkGray"/>
    </Grid>

And i added a try-catch to the script so you can debug easier:

        try
        {
            string richText = new TextRange(rtb1.Document.ContentStart, rtb1.Document.ContentEnd).Text;
            Console.WriteLine(richText);
            MessageBox.Show(richText);
        } catch (System.Windows.Markup.XamlParseException ex)
        {
            Console.WriteLine(ex.StackTrace);
        }

It works for me

  • Related