【发布时间】:2019-01-12 10:49:55
【问题描述】:
Catel 在视图中显示字段验证的结果(在视图模型或模型中完成)时遇到问题:如果字段中有错误,则相应的文本框应该用红框标记。但由于某种原因,我没有得到这个工作。
这是一个非常简化的测试场景,视图模型有 2 个整数字段,验证规则要求两者的值都
public class MainViewModel : ViewModelBase
{
public MainViewModel() : base()
{ }
protected override async Task InitializeAsync()
{
await base.InitializeAsync();
}
protected override async Task CloseAsync()
{
await base.CloseAsync();
}
public override string Title { get { return "Test"; } }
public int Value1
{
get { return GetValue<int>(Value1Property); }
set { SetValue(Value1Property, value); }
}
public static readonly PropertyData Value1Property = RegisterProperty(nameof(Value1), typeof(int), 42 );
public int Value2
{
get { return GetValue<int>(Value2Property); }
set { SetValue(Value2Property, value); }
}
public static readonly PropertyData Value2Property = RegisterProperty(nameof(Value2), typeof(int), 99);
protected override void ValidateFields(List<IFieldValidationResult> validationResults)
{
if (Value1 >= 100)
{
validationResults.Add(FieldValidationResult.CreateError(Value1Property, "Value1 must be < 100" ));
}
if (Value2 >= 100)
{
validationResults.Add(FieldValidationResult.CreateError(Value1Property, "Value2 must be < 100"));
}
}
protected override void ValidateBusinessRules(List<IBusinessRuleValidationResult> validationResults)
{ }
}
}
请注意:在我的实际项目中,字段和验证将位于模型中,但出于测试原因,我将其剥离为仅视图和视图模型。
这个简单的视图将视图模型作为数据上下文:
<catel:Window x:Class="WPF_Catel_Validation.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:catel="http://schemas.catelproject.com">
<StackPanel Orientation="Vertical" HorizontalAlignment="Left">
<TextBox Text="{Binding Value1, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" Width="100" />
<TextBox Text="{Binding Value2, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" Width="100" />
</StackPanel>
</catel:Window>
视图和视图模型之间的连接有效。当在文本框中输入非数字文本时,该视图还会显示错误。带有 ValidateFields() 方法的视图模型也可以识别任何错误,但视图不会在文本框周围用红框显示这些验证错误。
我已经使用 Catel 5.8.0 和 .NET 4.7.2 进行了测试。我有点想知道 Catel 类的 ViewModelBase 是如何实现 INotifyDataErrorInfo 的,但是事件 ErrorsChanged 在该类中是不可见的。但总的来说,我不知道我的视图模型、我的视图、Catel 或其他任何东西是否有问题?我也没有找到任何关于 Catel 的最新文档。任何建议都非常感谢 - 谢谢!
【问题讨论】:
标签: wpf validation view viewmodel catel