Mvvm验证 - 模型o viewmodel? [英] Mvvm validation - model o viewmodel?
问题描述
您好,
我正在尝试在MVVM WPF C#应用程序中实现验证。
在MVVM模式中,是吗更好地在ViewModel的Model o中实现验证(使用IDataErrorInfo)?
我尝试过:
目前我已在Model部分内实现验证。
ViewModel :
Hello,
i'm trying to implement the validation in MVVM WPF C# application.
In the MVVM Pattern, is it better to implement the validation (with IDataErrorInfo) in the Model o in the ViewModel?
What I have tried:
At the moment i've implement the validation inside the Model part.
ViewModel:
private Order selectedOrder;
public Order SelectedOrder
{
get
{
return selectedOrder;
}
set
{
selectedOrder= value;
OnPropertyChanged("SelectedOrder");
}
}
作为模型的一部分,我有类订单的定义:
as part of the model i have the definition of the class Order:
public class Order : Notifier, IDataErrorInfo
{
private string _NumOrder = "";
public string NumOrder
{
get
{
return _NumOrder;
}
set
{
_NumOrder = value;
OnPropertyChanged("NumOrder");
}
}
#region IDataErrorInfo
string IDataErrorInfo.Error
{
get
{
return null;
}
}
string IDataErrorInfo.this[string propertyName]
{
get
{
return GetValidationError(propertyName);
}
}
#endregion
#region Validation
static readonly string[] ValidateProperty =
{
"NumOrder"
};
public bool IsValid
{
get
{
foreach(string property in ValidateProperty)
if (GetValidationError(property) != null)
return false;
return true;
}
}
public string ValidateOrder()
{
if (String.IsNullOrWhiteSpace(numOrder))
{
return "Error, i need a value";
}
return null;
}
string GetValidationError(String propertyName)
{
string error = null;
switch (propertyName)
{
case "NumOrder":
error = ValidateOrder();
break;
}
return error;
}
#endregion
}
在视图中我正在尝试显示错误,但它不起作用。
In the View i'm trying to display the error, but it doesn't work.
<TextBox x:Name="txtNumOrder" FontSize="14" IsEnabled="{Binding ActionInRun,ConverterParameter=NumOrder, Converter={StaticResource EnumToBoolean}}" Text="{Binding SelectedOrder.numOrder, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>
<Label FontSize="12" x:Name="lblNote" Content="{Binding ElementName=numOrder, Path=(Validation.Errors).CurrentItem.ErrorContent}" />
因为在文本框字段中验证工作正常,但标签不显示错误消息。
如何正确显示错误?
提前谢谢
Because in the textbox field the validation works correctly, but the label don't show the error message.
How can i display the error correctly?
Thanks in advance
推荐答案
应在视图或视图模型中执行验证。查看本文: WPF中的验证 [ ^ ]
Validation should be performed in the view or viewmodel. Check this article: Validation in WPF[^]
这篇关于Mvvm验证 - 模型o viewmodel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!