我需要帮助实现INotifyDataErrorInfo接口,SfTextBoxEx放置在SfTextInputLayout中。
WPF与MVVM使用Caliburn.Micro框架。
请找到以下项目结构以通过问题来理解。
1(文件夹名称:基础结构文件:ValidatedPropertyChangedBase.cs
--它包含INotifyDataErrorInfo的实现。
2(文件夹名称:型号文件:TestModel.cs--包含从ValidatedPropertyChangedBase继承的两个属性--还包含使用FluentValidation 验证属性的类
4(文件夹名称:视图文件:HomeView.xaml--带有两个SfTextInputLayout和SfTextBoxExt 的标准窗口
4(文件夹名称:ViewModel文件:HomeViewModel.cs--以"模型"作为属性并触发"验证"的标准视图模型。--在这里,如果我在验证方法上设置断点,我可以看到返回的错误是正确的,但不知何故,它并没有触发UI显示错误消息。--在将属性与文本框绑定时,我已将ValidatesNottifyDataError设置为true。
如果有什么问题,请检查并指导我。注意:我正在使用syncfusion控件,但我也尝试了使用标准文本框,它不会触发errorchanged事件。
此外,我还使用了来自以下位置的IntoifyDataError实现:https://www.thetechgrandma.com/2017/05/wpf-prism-inotifydataerrorinfo-and.html
--已验证属性已更改基本
public abstract class ValidatedPropertyChangedBase : PropertyChangedBase, INotifyDataErrorInfo
{
private readonly Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>();
public void SetError(string propertyName, string errorMessage)
{
if (!_errors.ContainsKey(propertyName))
_errors.Add(propertyName, new List<string> { errorMessage });
RaiseErrorsChanged(propertyName);
}
protected void ClearError(string propertyName)
{
if (_errors.ContainsKey(propertyName))
_errors.Remove(propertyName);
RaiseErrorsChanged(propertyName);
}
protected void ClearAllErrors()
{
var errors = _errors.Select(error => error.Key).ToList();
foreach (var propertyName in errors)
ClearError(propertyName);
}
public void RaiseErrorsChanged(string propertyName)
{
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { return; };
public bool HasErrors
{
get { return _errors.Any(x => x.Value != null && x.Value.Count > 0); }
}
public IEnumerable GetErrors(string propertyName)
{
if (String.IsNullOrEmpty(propertyName) ||
!_errors.ContainsKey(propertyName)) return null;
return _errors[propertyName];
}
}
--ViewModel
public class HomeViewModel : ValidatedPropertyChangedBase
{
private TestModel _model;
public TestModel Model
{
get { return _model; }
set
{
if (_model != value)
{
_model = value;
NotifyOfPropertyChange(() => Model);
}
}
}
public HomeViewModel()
{
Model = new TestModel();
}
public void ValidateData()
{
ClearAllErrors();
var validator = new TestModelValidation();
FluentValidation.Results.ValidationResult result = validator.Validate(Model);
foreach (var error in result.Errors)
{
SetError(error.PropertyName, error.ErrorMessage);
}
if (result.IsValid)
{
MessageBox.Show("Data good to save !");
}
}
}
--查看
<Window
x:Class="ValidationDemo.Views.HomeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:convertor="clr-namespace:ValidationDemo.Infrastructure"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ValidationDemo.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sf="http://schemas.syncfusion.com/wpf"
Title="HomeView"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.Resources>
<Style
TargetType="sf:SfTextInputLayout">
<Setter Property="Width" Value="200" />
</Style>
</Window.Resources>
<StackPanel
HorizontalAlignment="Center"
VerticalAlignment="Center"
Orientation="Vertical">
<sf:SfTextInputLayout
Hint="First Name">
<sf:SfTextBoxExt
Text="{Binding Path=Model.FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" />
</sf:SfTextInputLayout>
<sf:SfTextInputLayout
Hint="Last Name">
<sf:SfTextBoxExt
Text="{Binding Path=Model.FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" />
</sf:SfTextInputLayout>
<TextBox
Text="{Binding Path=Model.FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" />
<TextBox
Text="{Binding Path=Model.FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" />
<Button
x:Name="ValidateData"
Content="Validate Data" />
</StackPanel>
--实施Fluent验证的模型:
public class TestModel : ValidatedPropertyChangedBase
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
if (_firstName != value)
{
_firstName = value;
NotifyOfPropertyChange(() => FirstName);
}
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
if (_lastName != value)
{
_lastName = value;
NotifyOfPropertyChange(() => LastName);
}
}
}
}
public class TestModelValidation:AbstractValidator<TestModel>
{
public TestModelValidation()
{
RuleFor(t => t.FirstName)
.NotEmpty()
.WithMessage("Please enter first name");
RuleFor(t => t.FirstName)
.NotEmpty()
.WithMessage("Please enter last name");
}
}
能够解决这个问题,是通过控制暴露视图模型中的HasError。
ErrorText="{Binding RelativeSource={RelativeSource Mode=Self}, Path=InputView.(Validation.Errors), Converter={StaticResource EC}}"
HasError="{Binding RelativeSource={RelativeSource Mode=Self}, Path=InputView.(Validation.Errors), Converter={StaticResource ECO}}"
添加了带有转换器的控件的属性,从而解决了问题。