我有 ItemType ,它在 IDataErrorInfo 接口的帮助下实现了验证所需的一切:
#region IDataErrorInfo implementation
//WPF doesn't need this one
public string Error
{ get { return null; } }
public string this[string propertyName]
{
get { return GetValidationError(propertyName); }
}
#endregion
#region Validation
public bool IsValid
{
get
{
foreach (string property in ValidatedProperties)
{
if (GetValidationError(property) != null)
{
return false;
}
}
return true;
}
}
static readonly string[] ValidatedProperties =
{
"Name"
};
private string GetValidationError(string propertyName)
{
if (Array.IndexOf(ValidatedProperties, propertyName) < 0)
return null;
string error = null;
switch (propertyName)
{
case "Name":
error = ValidateName();
break;
default:
Debug.Fail("Unexpected property being validated on Customer: " + propertyName);
break;
}
return error;
}
string ValidateName()
{
if (!IsStringMissing(Name))
{
return "Name can not be empty!";
}
return null;
}
static bool IsStringMissing(string value)
{
return string.IsNullOrEmpty(value) ||
value.Trim() == String.Empty;
}
#endregion
ItemType 用 ItemViewModel 包装。在 ItemViewModel 上,当用户单击“保存”按钮时,我有一个命令:
public ICommand SaveItemType
{
get
{
if (saveItemType == null)
{
saveItemType = new RelayCommand(() => Save());
}
return saveItemType;
}
}
然后,在 DetailsView 中,我有以下 xaml 代码:
<TextBlock Text="Name:" />
<TextBox Grid.Column="1" Name="NameTextBox" Text="{Binding Name, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
Validation.ErrorTemplate="{x:Null}" />
<ContentPresenter Grid.Row="13" Grid.Column="2"
Content="{Binding ElementName=NameTextBox, Path=(Validation.Errors).CurrentItem}" />
下面的架构正在发生(目前还不清楚,但表单实际上是一个独立的xaml文件(用户控件),其中表单中网格的datacontext设置为ObservableCollection):
<Grid DataContext="{Binding Items}">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
我遇到的问题是错误消息没有显示。当我断点并检查它是否正确验证以及是否有任何错误消息时,我确实有它们。但不知何故,错误消息没有到达 xaml 中。
拼图中缺失的一块是什么?
编辑 - 缺失的部分
是的,所以,事情是这样的:
我在模型上实现了 IDataErrorInfo,但没有在包装模型的 ViewModel 上实现。我所要做的就是在 ViewModel 上实现 IDataErrorInfo 接口,并从模型中获取它。
IDataErrorInfo 的 ViewModel 实现:
{ get { return (ItemType as IDataErrorInfo).Error; } }
public string this[string propertyName]
{
get
{
return (ItemType as IDataErrorInfo)[propertyName];
}
}