wpf mvvm 文本输入内容限定指定内容
项目中遇到部分场景需要用到限定的内容,例如输入的是(数字,或英文或字符等)
项目中采用mvvm的设计模式
<ItemsControl Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="{Binding VoteType,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource GenericTypeCvt},ConverterParameter='2:Visible|other:Collapsed'}" Background="Transparent" ItemsSource="{Binding Option.voteTagList}" BorderThickness="0" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,20,0,0" >
<StackPanel Orientation="Horizontal" Margin="0,0,60,0" Width="370">
<Label Content="{Binding num}" Foreground="{Binding color}" FontWeight="Bold" FontSize="30" FontFamily="{StaticResource ElementIcon}" Margin="0,0,10,0"></Label>
<!--<Label Content="{Binding tagWords}" Foreground="#999999" FontWeight="Bold" FontFamily="{StaticResource ElementIcon}"></Label>-->
<!--<Label Content="{Binding tagWords}" Foreground="#999999" FontWeight="Bold" FontSize="30" FontFamily="{StaticResource ElementIcon}"></Label>-->
<TextBlock Text="{Binding tagWords}" Foreground="#999999" FontWeight="Bold" FontSize="34" FontFamily="{StaticResource ElementIcon}" Width="320" TextTrimming="CharacterEllipsis"></TextBlock>
</StackPanel>
<TextBox VerticalAlignment="Center" Width ="240" Height=" 40" FontSize="30" FontFamily="{StaticResource ElementIcon}" Text="{Binding tagScore,Mode=TwoWay}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
- 从UI的层面去做输入限定,创建一个文本
textbox
覆盖该OnPreviewTextInput
方法的简单子类型,决定从那限定其输入的内容
public class MemTextBox : TextBox
{
private static readonly Regex regex = new Regex("^[a-zA-Z]+$");//限定输入英文
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
if (!regex.IsMatch(e.Text))
e.Handled = true;
base.OnPreviewTextInput(e);
}
}
- 在vm中,对输入的内容进行限定,由于v 绑定的是选项的「对象」的一个子项。所以需要对整个对象进行for 循环取值然后对其内容进行判断。后台取值然后对内容进行限定。由于是循环消耗性能,取值进行判断等一系列的操作。
for (int i = 0; i < Option.voteTagList.Count; i++)
{
Ballot ballot = new Ballot();
ballot.createTime = NowTime;
ballot.id = Option.id;
ballot.tagScore = Option.voteTagList[i].tagScore;
var dd = Option.voteTagList[i].tagScore;
if (!Regex.IsMatch(dd, @"^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$"))
{
ballot.tagScore = dd;
}
ballot.tagWords = Option.voteTagList[i].tagWords;
ballot.username = Global.UserName;
ballot.usernameList = null;
ballot.voteId = _Voteid;
ballot.voteNum = Option.voteTagList.Count;
ballots.Add(ballot);
}
- 通过文本预览事件与正则区配,定义正则,与输入的内容进行区配,正常下已经处理完成,但存在中文输入法输入时,会有问题
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下