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

WPF TextBox样式设置:如何禁用滚动功能?

禁用WPF TextBox的滚动功能解决方案

方法1:修改模板中的ScrollViewer属性

在你的TextBox模板里,给PART_ContentHost这个ScrollViewer添加滚动禁用属性,直接关闭水平和垂直方向的滚动功能,同时隐藏滚动条:

<Style TargetType="{x:Type TextBox}"
       x:Key="textBox1">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border CornerRadius="16"
                        Background="{TemplateBinding Background}">
                    <ScrollViewer Margin="10,7.5"
                                  x:Name="PART_ContentHost"
                                  HorizontalScrollBarVisibility="Disabled"
                                  VerticalScrollBarVisibility="Disabled"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

方法2:通过附加属性直接设置TextBox

如果不想修改模板,可在使用TextBox时直接设置ScrollViewer的附加属性,同样能禁用滚动:

<TextBox Margin="0,0,20,0"
         Background="#F2E3D5"
         x:Name="Username"
         Style="{StaticResource textBox1}"
         Width="230"
         Height="35"
         FontSize="21"
         ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         ScrollViewer.VerticalScrollBarVisibility="Disabled">
</TextBox>

方法3:禁止鼠标滚轮触发滚动

若需防止用户通过鼠标滚轮触发滚动(部分场景下滚动条禁用后滚轮仍可能生效),可给TextBox添加PreviewMouseWheel事件并标记事件已处理:

XAML部分:

<TextBox ...
         PreviewMouseWheel="TextBox_PreviewMouseWheel">
</TextBox>

后台C#代码:

private void TextBox_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    e.Handled = true;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:06:27