如何使用WPF和C#对文本框条目仅接受数字,逗号,点和退格 [英] How can I do to textbox entry accept only number, comma, point and backspace with WPF and C#
本文介绍了如何使用WPF和C#对文本框条目仅接受数字,逗号,点和退格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个WPF表单。我需要做一些控件文本框只接受数字,点,逗号和退格。我对此有些困惑,因为我知道winform和winform代码在WPF项目中不起作用。
解决方案
您可以尝试使用
希望它有所帮助。
最诚挚的问候,
Bob
I have a form with WPF. I need to do some controls textbox to accept only number, point, comma and backspace. I'm having some dificult with this, because I know winform and winform code do not work in WPF project.
解决方案
Hi,
You can try to use ValidationRule Class to create a custom rule in order to check the validity of user input.
Below sample for your reference.
namespace wpfAppDemo.wpfDataValidation { public partial class sample1 : Window { public sample1() { InitializeComponent(); } } public class sample1_ViewModel { private string _name; public string Name { get { return _name; } set { _name = value; } } } public class StringValidationRule : ValidationRule { private string _errorMessage; public string ErrorMessage { get { return _errorMessage; } set { _errorMessage = value; } } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { string input = value.ToString(); bool rt = Regex.IsMatch(input, "^[0-9.,\\s]*
"); if (!rt) { return new ValidationResult(false,this.ErrorMessage); } else { return new ValidationResult(true, null); } } } }
<Window x:Class="wpfAppDemo.wpfDataValidation.sample1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:wpfAppDemo.wpfDataValidation" mc:Ignorable="d" Title="sample1" Height="300" Width="500"> <Window.DataContext> <local:sample1_ViewModel/> </Window.DataContext> <StackPanel> <!--PropertyChanged--> <TextBox Height="20" Margin="20" > <TextBox.Style> <Style TargetType="{x:Type TextBox}"> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <DockPanel LastChildFill="True"> <TextBlock DockPanel.Dock="Bottom" Foreground="Red" FontSize="10pt" Text="{Binding ElementName=MyAdorner,Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"> </TextBlock> <Border BorderBrush="Red" BorderThickness="2"> <AdornedElementPlaceholder Name="MyAdorner" /> </Border> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </TextBox.Style> <TextBox.Text> <Binding Path="Name" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <local:StringValidationRule ErrorMessage="input should only include number, comma, point and backspace " /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </StackPanel> </Window>How to: Implement Binding Validation
Hope it helps.
Best Regards,
Bob
这篇关于如何使用WPF和C#对文本框条目仅接受数字,逗号,点和退格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文