我有一个简单的对话框,其中包含以下编辑框:
<TextBox Text="{Binding Path=EmailSettings.SmtpServer, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" />
该对话框使用Model作为其数据上下文(为了简化模型示例,尚未显示INotifyPropertyChanged,也不是创建模型的代码, 将对话框数据上下文设置为模型实例):
class EmailSettingsModel : IDataErrorInfo
{
public EmailSettingsModel ()
{
EmailSettings = new EmailSettings();
}
public EmailSettings EmailSettings
{ get; set; }
string _error;
public string Error
{
get { return _error; }
set { _error = value; }
}
public string this[string propertyName]
{
get
{
string errorMessage = null;
if ( string.Compare( propertyName, "EmailSettings.SmtpServer" ) == 0 )
{
if ( !string.IsNullOrWhiteSpace( EmailSettings.SmtpServer ) )
errorMessage = "SMTP server is not valid";
}
Error = errorMessage;
}
}
}
模型包含一个属性,它是一个简单的POCO类,上面有几个属性。
class EmailSettings
{
public string SmtpServer
{ get; set; }
}
我无法启动IDataErrorInfo索引器并花费数小时查看。当我更改文本框上的绑定以使用简单属性时:
<TextBox Text="{Binding Path=SmtpServer, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" />
在模型上,IDataErrorInfo索引器被触发。
class EmailSettingsModel
{
public string SmtpServer
{ get; set; }
}
未调用IDataErrorInfo,因为我为绑定语句使用了复合属性。我已经使用这样的复杂属性进行常规数据绑定,但它们可以工作,但是对于这个例子,没有调用IDataErrorInfo。
答案 0 :(得分:3)
IDataErrorInfo仅在实现的级别触发
例如,如果您的Binding Path看起来像这个“viewModel.property1.property2.property3”,您将需要在viewModel类中以及property1类内部和property2类中实现IDataErrorInfo。 Property3是一个字符串。
因此,为了让它适用于您,只需在其他地方实现IDataErrorInfo。