WPF输入验证提示

WPF输入验证提示

在写前端输入时,我们经常要对用户的输入进行验证,检查输入的合理性,当输入非法时,需要能提醒用户。比如下图,当输入不是IP格式的字符串时,会提示输入正确格式的IP。

百度一圈得到的做法:

前端

 <TextBox Text="{Binding MccIP,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}" Style="{StaticResource txtboxValiStyle}" BorderThickness="0" Width="100" Height="30" Margin="5"/>

样式

    <!--textbox验证style-->
    <Style x:Key="txtboxValiStyle" TargetType="TextBox">
        <Setter Property="FontSize" Value="16"/>
        <Setter Property="Height" Value="34"/>
        <Setter Property="Width" Value="140"/>
        <Setter Property="Margin" Value="3 12 3 0"/>

        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="Validation.ErrorTemplate">
                    <Setter.Value>
                        <ControlTemplate>
                            <DockPanel LastChildFill="True">
                                <TextBlock DockPanel.Dock="Bottom" Background="Red" Foreground="White" FontSize="12" Height="14"
                                                       Width="Auto"
                                                       VerticalAlignment="Center" TextAlignment="Center" TextWrapping="Wrap" FontFamily="Arial" 
                                                 Text="{Binding ElementName=ErrorBox, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                                </TextBlock>
                                <AdornedElementPlaceholder Name="ErrorBox" />
                            </DockPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>

在样式中判断,Property="Validation.HasError" Value="true",触发样试更改。

后端

测试使用的MVVM框架为Caliburn.Micro

using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;  
namespace DataError.ViewModels
{
    public class MainViewModel : Screen, INotifyPropertyChanged, IDataErrorInfo
    {
        private string mccIP;

        [Required]
        [RegularExpression(@"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$", ErrorMessage = "请输入正确格式的IP地址!")]
        public string MccIP
        {
            get { return mccIP; }
            set { mccIP = value; NotifyOfPropertyChange(); }
        }

        #region 实现IDataErrorInfo接口
        public string Error
        {
            get { return null; }
        }

        public string this[string columnName]
        {
            get
            {
                var vc = new ValidationContext(this, null, null);
                vc.MemberName = columnName;
                var res = new List<ValidationResult>();
                var result = Validator.TryValidateProperty(this.GetType().GetProperty(columnName).GetValue(this, null), vc, res);
                if (res.Count > 0)
                {
                    return string.Join(Environment.NewLine, res.Select(r => r.ErrorMessage).ToArray());
                }
                return string.Empty;
            }
        }
        #endregion
    }
}

首先在ViewModel的类中需继承IDataErrorInfo接口,并在类中实现IDataErrorInfo接口,然后使用正则表达式判断字符串格式,如果格式不匹配,输出错误消息,如下图。

posted @ 2022-11-16 15:24  修行的蜗牛  阅读(132)  评论(0编辑  收藏  举报