【问题标题】:Required field Validation in WPF text boxWPF 文本框中的必填字段验证
【发布时间】:2017-03-12 17:20:28
【问题描述】:

我需要一种简单的方法来验证文本框(必填字段)。当用户按下按钮时,它应该检查所有必填字段是否存在。

我试过这段代码:

<Window.Resources>
    <ControlTemplate x:Key="validationTemplate">
        <DockPanel>
            <TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right" />
            <AdornedElementPlaceholder/>
        </DockPanel>
    </ControlTemplate>
</Window.Resources>
<Grid>
    <Button Content="Button" HorizontalAlignment="Left" Height="26" Margin="62,213,0,0" VerticalAlignment="Top" Width="121" Click="Button_Click_1"/>
    <TextBox x:Name="txtEmail1" Text="" Height="61" Margin="116,10,194,0" Validation.ErrorTemplate="{StaticResource validationTemplate}"/>
</Grid>

请任何人提出一种在 WPF 的文本框中进行验证的方法。 谢谢

【问题讨论】:

    标签: c# wpf validation textbox


    【解决方案1】:

    您应该将TextBoxText 属性绑定到视图模型的属性,并在视图模型类中实现IDataErrorInfo 接口。

    请参考以下示例代码。

    代码:

    public partial class Window3 : Window
    {
        Window3ViewModel viewModel = new Window3ViewModel();
        public Window3()
        {
            InitializeComponent();
            DataContext = viewModel;
        }
    
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            viewModel.Validate();
        }
    }
    
    public class Window3ViewModel : INotifyDataErrorInfo
    {
        private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();
    
        public void Validate()
        {
            bool isValid = !string.IsNullOrEmpty(_text);
            bool contains = _validationErrors.ContainsKey(nameof(Text));
            if (!isValid && !contains)
                _validationErrors.Add(nameof(Text), "Mandatory field!");
            else if (isValid && contains)
                _validationErrors.Remove(nameof(Text));
    
            if (ErrorsChanged != null)
                ErrorsChanged(this, new DataErrorsChangedEventArgs(nameof(Text)));
        }
    
        public bool HasErrors => _validationErrors.Count > 0;
    
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
    
        public IEnumerable GetErrors(string propertyName)
        {
            string message;
            if (_validationErrors.TryGetValue(propertyName, out message))
                return new List<string> { message };
    
            return null;
        }
    
        private string _text;
        public string Text
        {
            get { return _text; }
            set
            {
                _text = value; 
            }
        }
    }
    

    XAML:

    <Window x:Class="WpfApp2.Window3"
            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:WpfApp2"
            mc:Ignorable="d"
            Title="Window3" Height="300" Width="300">
        <Window.Resources>
            <ControlTemplate x:Key="validationTemplate">
                <DockPanel>
                    <TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right" />
                    <AdornedElementPlaceholder/>
                </DockPanel>
            </ControlTemplate>
        </Window.Resources>
        <Grid>
            <Button Content="Button" HorizontalAlignment="Left" Height="26" Margin="62,213,0,0" VerticalAlignment="Top" Width="121" Click="Button_Click_1"/>
            <TextBox x:Name="txtEmail1" Text="{Binding Text}" Height="61" Margin="116,10,194,0" Validation.ErrorTemplate="{StaticResource validationTemplate}"/>
        </Grid>
    </Window>
    

    有关 WPF 中数据验证的工作原理的更多信息,请参阅以下博客文章。

    WPF 中的数据验证: https://blog.magnusmontin.net/2013/08/26/data-validation-in-wpf/

    【讨论】:

      【解决方案2】:

      我将向您展示如何使用 IDataErrorInfo 验证数据。这个接口只有两个需要实现的成员:

      公共字符串错误{get; } - 得到一条错误信息,指出这个对象有什么问题 公共字符串 this[string columnName] { get; } - 获取具有给定名称的属性的错误消息。 实现 IDataErrorInfo 后,您需要在要验证的元素中将 ValidatesOnDataErrors 设置为 true。为了简化代码示例,我在 MainViewModel 中实现了 IDataErrorInfo,如下所示:

      public class MainViewModel : BindableBase, IDataErrorInfo
      {
          private string _firstName;
          private string _lastName;
      
          public string FirstName
          {
              get { return _firstName; }
              set { _firstName = value; RaisePropertyChanged(); }
          }              
      
          public string LastName
          {
              get { return _lastName; }
              set { _lastName = value; RaisePropertyChanged(); }
          }
      
          public string this[string columnName]
          {
              get
              {
                  string error = string.Empty;
      
                  switch (columnName)
                  {
                      case nameof(FirstName):
                          if (string.IsNullOrWhiteSpace(FirstName))
                              error = "First name cannot be empty.";
                          if (FirstName?.Length > 50)
                              error = "The name must be less than 50 characters.";
                          break;
      
                      case nameof(LastName):
                          if (string.IsNullOrWhiteSpace(LastName))
                              error = "Last name cannot be empty.";
                          break;
                  }
      
                  return error;
              }
          }
      
          public string Error => string.Empty;
      }
      

      TextBox 元素中,我将 ValidatesOnDataErrors 设置为 true

      <TextBox Text="{Binding FirstName, Mode=TwoWay,
                  UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
      

      【讨论】:

        猜你喜欢
        • 2015-02-20
        • 1970-01-01
        • 2017-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多