【发布时间】:2016-03-17 08:23:03
【问题描述】:
在 WPF 项目中,我正在使用 INotifyDataErrorInfo 实现验证 TextBox 输入。可能会出现多个错误。
当我输入导致多个错误的内容时,会显示所有验证错误。但是,当我修复一个错误时,验证消息不会改变,这意味着会显示错误的错误消息。只有当我修复所有错误时,消息才会消失。
这是我的实现有问题,还是 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();
}
}
}
目标 .net 版本是 4.5
编辑:
遇到IDataErrorInfo 的类似问题,请参阅此问题:
Validation Rule not updating correctly with 2 validation rules
更换转换器有帮助
【问题讨论】:
标签: c# wpf validation