You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中RichTextBox输入后后台获取文本始终为初始占位值怎么办

问题根因

你读不到新输入内容的核心原因是用户实际输入的内容根本没有进入RichTextBox,全部写到了下层叠放的占位符TextBox里,RichTextBox的文档始终停留在初始状态,自然读不到更新。
对应你XAML里的配置问题:

  • 你给名为rtb1的RichTextBox设置了HorizontalAlignment="Right",且没有指定宽度,导致控件不会拉伸占满整个Grid单元格,只会靠右占据和初始内容"Hallo"宽度匹配的窄条区域,单元格剩下的绝大多数区域都没有被RichTextBox覆盖。
  • 虽然你给RichTextBox设置了更高的Panel.ZIndex=2,但控件未覆盖的区域,命中测试会直接落到下层ZIndex=1的tb1控件上。你点击这些区域输入的内容,全部会写入下层的tb1,你视觉上看到的"输入后内容正常显示",其实是tb1渲染的输入内容,和rtb1没有关系。
  • 你原本用叠放TextBox的方式做RichTextBox的占位提示,但没有给占位TextBox禁用命中测试,进一步放大了输入漏到下层控件的问题。
修复步骤
  • 修正RichTextBox的布局属性,删除HorizontalAlignment="Right"配置,使用默认的Stretch对齐让RichTextBox完全占满整个Grid单元格,保证所有输入区域的交互都能落到RichTextBox上。
  • 给占位用的tb1加上IsHitTestVisible="False"属性,从根源上禁止占位TextBox接收鼠标、键盘输入,彻底避免抢焦点的问题。
  • 补全占位符的显隐逻辑,在你已经绑定的OnDocumentChanged事件中,根据RichTextBox的内容是否为空,控制占位文本的显示/隐藏。
  • 读取RichTextBox文本时加Trim()处理,去掉FlowDocument默认带的首尾段落换行符,拿到干净的输入内容。
参考代码

修正后的XAML片段:

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

后台事件及读取文本的代码:

private void OnDocumentChanged(object sender, TextChangedEventArgs e)
{
    string currentText = new TextRange(rtb1.Document.ContentStart, rtb1.Document.ContentEnd).Text.Trim();
    // 有输入内容时隐藏占位符,无内容时显示占位符
    tb1.Visibility = string.IsNullOrEmpty(currentText) ? Visibility.Collapsed : Visibility.Visible;
}

// 读取RichTextBox实际输入内容的代码
string richText = new TextRange(rtb1.Document.ContentStart, rtb1.Document.ContentEnd).Text.Trim();
MessageBox.Show(richText);

内容的提问来源于stack exchange,提问作者user19384619

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 19:45:59