2016-03-17 61 views
0

在WPF项目中,我使用INotifyDataErrorInfo实现验证了TextBox输入。可能会发生多个错误。INotifyDataErrorInfo多个验证错误,旧消息不会消失

当我输入导致多个错误的内容时,显示所有验证错误。但是,当我修复一个错误时,验证消息不会更改,这意味着会显示错误的错误消息。只有当我修复所有错误时,消息才会消失。

这是我的实现问题,还是WPF实现只重新获取验证消息,如果HasErrors更改?但是,通过调试器遍历它,我可以看到GetErrors和HasErrors都被调用。

步骤来重现与附例如:

  • 输入333333. 2验证消息被示出。
  • 将前导3更改为2.尽管第一个错误已修复,但仍会显示两条验证消息。
  • 将第二个3更改为0.两个消息都消失
  • 将第二个数字再次更改为3。显示第二个验证消息。
  • 再次将前导数字更改为3。只显示第二条验证消息,尽管它应该同时显示。

是的,这个例子没有多大意义,因为我实际上可以摆脱第一次检查,因为它包含在第二次检查中。

的视图:

<Window x:Class="WeirdValidationTest.ValidationTestView" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WeirdValidationTest" 
     Height="60" Width="400"> 
    <Window.DataContext> 
     <local:ValidationTestViewModel /> 
    </Window.DataContext> 
    <Window.Resources> 
     <local:ValidationErrorsToStringConverter x:Key="ValErrToString" /> 
     <ControlTemplate x:Key="ErrorTemplate"> 
      <Border BorderBrush="Red" BorderThickness="1"> 
       <StackPanel Orientation="Horizontal"> 
        <AdornedElementPlaceholder /> 
        <TextBlock Text="{Binding Converter={StaticResource ValErrToString}}" Background="White" /> 
       </StackPanel> 
      </Border> 
     </ControlTemplate> 
    </Window.Resources> 
    <Grid> 
     <TextBox MaxLength="6" Validation.ErrorTemplate="{StaticResource ErrorTemplate}" 
       Text="{Binding InputValue, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" 
       VerticalAlignment="Top" Width="100" /> 
    </Grid> 
</Window> 

(代码隐藏在构造简单InitializeComponent调用)

的视图模型:

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Runtime.CompilerServices; 

namespace WeirdValidationTest 
{ 
    internal class ValidationTestViewModel : INotifyPropertyChanged, INotifyDataErrorInfo 
    { 
     private readonly Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>(); 
     private uint inputValue; 

     public event PropertyChangedEventHandler PropertyChanged; 

     public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; 

     public uint InputValue 
     { 
      get 
      { 
       return inputValue; 
      } 
      set 
      { 
       if (inputValue != value) 
       { 
        if (value/100000 == 2) 
        { 
         RemoveError("InputValue", 
            String.Format("Must be in range {0}...{1}", "200000", "299999")); 
        } 
        else 
        { 
         AddError("InputValue", 
           String.Format("Must be in range {0}...{1}", "200000", "299999")); 
        } 

        uint testNumber = (uint) ((value)/1e4); 

        { 
         string msg = string.Format("Must start with value {0}", "20...."); 
         if (testNumber != 20) 
         { 
          AddError("InputValue", msg); 
         } 
         else 
         { 
          RemoveError("InputValue", msg); 
         } 
        } 

        inputValue = value; 
        OnPropertyChanged(); 
       } 
      } 
     } 

     public bool HasErrors 
     { 
      get 
      { 
       return errors.Count != 0; 
      } 
     } 

     public IEnumerable GetErrors(string propertyName) 
     { 
      List<string> val; 
      errors.TryGetValue(propertyName, out val); 
      return val; 
     } 

     void AddError(string propertyName, string messageText) 
     { 
      List<string> errList; 
      if (errors.TryGetValue(propertyName, out errList)) 
      { 
       if (!errList.Contains(messageText)) 
       { 
        errList.Add(messageText); 
       } 
      } 
      else 
      { 
       errList = new List<string> { messageText }; 
       errors.Add(propertyName, errList); 
      } 
      OnErrorsChanged(propertyName); 
     } 

     void RemoveError(string propertyName, string messageText) 
     { 
      List<string> errList; 
      if (errors.TryGetValue(propertyName, out errList)) 
      { 
       errList.Remove(messageText); 
       if (errList.Count == 0) 
       { 
        errors.Remove(propertyName); 
       } 
      } 
      OnErrorsChanged(propertyName); 
     } 

     private void OnErrorsChanged(string propertyName) 
     { 
      var handler = ErrorsChanged; 
      if (handler != null) 
      { 
       handler(this, new DataErrorsChangedEventArgs(propertyName)); 
      } 
     } 

     private void OnPropertyChanged([CallerMemberName] string propertyName = "") 
     { 
      var handler = PropertyChanged; 
      if (handler != null) 
      { 
       handler(this, new PropertyChangedEventArgs(propertyName)); 
      } 
     } 
    } 
} 

变换器:

using System; 
using System.Collections.ObjectModel; 
using System.Globalization; 
using System.Linq; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 

namespace WeirdValidationTest 
{ 
    [ValueConversion(typeof(ReadOnlyObservableCollection<ValidationError>), typeof(string))] 
    internal class ValidationErrorsToStringConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      var errorCollection = value as ReadOnlyObservableCollection<ValidationError>; 

      if (errorCollection == null) 
      { 
       return DependencyProperty.UnsetValue; 
      } 

      return String.Join(", ", errorCollection.Select(e => e.ErrorContent.ToString())); 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, 
            CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 
} 

目标。净版本4.5

编辑: 打一个类似的问题与IDataErrorInfo,看到了这个问题: Validation Rule not updating correctly with 2 validation rules 更改转换器有助于

回答

1

很好解释,你的代码看起来相当不错。我用你的方式解决了你的问题,希望你喜欢它。 只需更改您的AddError和RemoveError方法就可以,

void AddError(string propertyName, string messageText) 
     { 
      List<string> errList; 
      if (errors.TryGetValue(propertyName, out errList)) 
      { 
       if (!errList.Contains(messageText)) 
       { 
        errList.Add(messageText); 
        errors.Remove(propertyName); 
        OnErrorsChanged(propertyName); 
        if (errList != null) 
         errors.Add(propertyName, errList); 
       } 
      } 
      else 
      { 
       errList = new List<string> { messageText }; 
       errors.Add(propertyName, errList); 
       OnErrorsChanged(propertyName); 
      } 
     } 
     void RemoveError(string propertyName, string messageText) 
     { 
      List<string> errList; 
      if (errors.TryGetValue(propertyName, out errList)) 
      { 
       errList.Remove(messageText); 
       errors.Remove(propertyName); 
      } 
      OnErrorsChanged(propertyName); 
      if (errList != null) 
       errors.Add(propertyName, errList); 

     } 
+0

适合我,谢谢。只有2个问题:为什么在这两种方法中没有最终的OnErrorsChanged(Works without,但我实际上会猜测它是需要的)?那么errList!= null检查方法的末尾是什么(它应该是在方法的开始,我想我只是在我的例子中忘了它) –