06 WPF之TextBox

WPF TextBox 使用详解

WPF TextBox 基础用法

在 WPF 中,TextBox 是一个常用的输入控件,支持文本编辑、多行输入、数据绑定等功能。以下是基本使用方法:

<TextBox Width="200" Height="30" Text="默认文本"/>

TextBox 常用属性

  • Text:获取或设置文本框的文本内容。
  • MaxLength:限制输入的最大字符数。
  • IsReadOnly:设置为 true 时,文本框为只读状态。
  • TextWrapping:控制文本换行方式(WrapNoWrap)。
  • AcceptsReturn:设置为 true 时允许多行输入。
  • VerticalScrollBarVisibility:显示垂直滚动条(Auto/Visible/Hidden)。
<TextBox 
    Text="多行文本" 
    TextWrapping="Wrap" 
    AcceptsReturn="True"
    VerticalScrollBarVisibility="Auto"
    Height="100"/>

TextBox 数据绑定

通过 Binding 实现与视图模型(ViewModel)的数据同步:

<TextBox Text="{Binding UserName, UpdateSourceTrigger=PropertyChanged}"/>

  • UpdateSourceTrigger=PropertyChanged 表示文本变化时立即更新绑定源。

事件处理

常用事件包括 TextChangedGotFocusLostFocus 等:

<TextBox TextChanged="TextBox_TextChanged"/>

后台代码处理事件:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    var textBox = (TextBox)sender;
    Debug.WriteLine(textBox.Text);
}

自定义样式

通过 StyleControlTemplate 自定义外观:

<Style TargetType="TextBox">
    <Setter Property="Background" Value="LightYellow"/>
    <Setter Property="BorderBrush" Value="Gray"/>
    <Setter Property="FontSize" Value="14"/>
</Style>

输入验证

通过 ValidationRuleINotifyDataErrorInfo 实现验证逻辑:

<TextBox>
    <TextBox.Text>
        <Binding Path="Age">
            <Binding.ValidationRules>
                <local:NumberValidationRule Min="1" Max="100"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

水印效果(Placeholder)

通过附加属性或自定义控件实现提示文本:

<TextBox local:TextBoxHelper.Watermark="请输入用户名..."/>

高级功能

  • SpellCheck:启用拼写检查(SpellCheck.IsEnabled="True")。
  • InputScope:优化虚拟键盘输入(如 NumberEmail 等)。
<TextBox SpellCheck.IsEnabled="True" InputScope="Number"/>

以上内容涵盖了 TextBox 的核心功能,可根据实际需求组合使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值