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

WPF自定义带提示文本的TextBox样式后获取Text属性始终为空问题

问题根源

你自定义的TextBox控件模板存在逻辑错误:你在模板内部额外嵌套了一个独立的TextBox(命名为SearchBox),你实际在界面上输入的内容都存储在这个内部子TextBox的Text属性中,和外部你命名为txtbox的外层TextBox没有任何绑定关系,因此后台读取txtbox.Text永远为空。

正确修改方案

WPF原生TextBox的控件模板约定使用名为PART_ContentHost的ScrollViewer作为文本输入的内容宿主,不需要额外嵌套TextBox,同时用TemplateBinding/RelativeSource TemplatedParent绑定到外层控件的属性即可。修改后的样式如下:

<Style TargetType="{x:Type TextBox}"
       x:Key="SearchBoxTheme">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border CornerRadius="10"
                        Width="{TemplateBinding Width}"
                        Background="#3d5a80">
                    <Grid>
                        <Rectangle StrokeThickness="1"/>
                        <!-- 用约定的内容宿主替代嵌套的TextBox -->
                        <ScrollViewer x:Name="PART_ContentHost"
                                      FontSize="17"
                                      Foreground="#e0fbfc"
                                      BorderThickness="0"
                                      Background="Transparent"
                                      Padding="5"/>
                        
                        <TextBlock IsHitTestVisible="False"
                                   Text="Hint Text..."
                                   FontSize="17" 
                                   Foreground="#e0fbfc"
                                   Background="Transparent"
                                   Margin="6,0,10,0">
                            <TextBlock.Style>
                                <Style TargetType="{x:Type TextBlock}">
                                    <Setter Property="Visibility" Value="Hidden"/>
                                    <Style.Triggers>
                                        <!-- 绑定到模板父级(外层TextBox)的Text属性 -->
                                        <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource TemplatedParent}}" Value="">
                                            <Setter Property="Visibility" Value="Visible"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </TextBlock.Style>
                        </TextBlock>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

修改后你在界面输入的内容会直接同步到外层txtbox的Text属性,后台读取就能拿到正确值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:09:05