WPF TextBox 基础用法
在 WPF 中,TextBox 是一个常用的输入控件,支持文本编辑、多行输入、数据绑定等功能。以下是基本使用方法:
<TextBox Width="200" Height="30" Text="默认文本"/>
TextBox 常用属性
- Text:获取或设置文本框的文本内容。
- MaxLength:限制输入的最大字符数。
- IsReadOnly:设置为
true时,文本框为只读状态。 - TextWrapping:控制文本换行方式(
Wrap或NoWrap)。 - 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表示文本变化时立即更新绑定源。
事件处理
常用事件包括 TextChanged、GotFocus、LostFocus 等:
<TextBox TextChanged="TextBox_TextChanged"/>
后台代码处理事件:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (TextBox)sender;
Debug.WriteLine(textBox.Text);
}
自定义样式
通过 Style 和 ControlTemplate 自定义外观:
<Style TargetType="TextBox">
<Setter Property="Background" Value="LightYellow"/>
<Setter Property="BorderBrush" Value="Gray"/>
<Setter Property="FontSize" Value="14"/>
</Style>
输入验证
通过 ValidationRule 或 INotifyDataErrorInfo 实现验证逻辑:
<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:优化虚拟键盘输入(如
Number、Email等)。
<TextBox SpellCheck.IsEnabled="True" InputScope="Number"/>
以上内容涵盖了 TextBox 的核心功能,可根据实际需求组合使用。
WPF TextBox 使用详解
9882

被折叠的 条评论
为什么被折叠?



