我有一个简单的对话框,其中包含如下编辑框:
<TextBox Text="{Binding Path=EmailSettings.SmtpServer, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" />
该对话框使用模型作为其数据上下文(为了简化模型示例,未显示 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 索引器并花了数小时寻找。当我将文本框上的绑定(bind)更改为使用简单属性时:
<TextBox Text="{Binding Path=SmtpServer, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" />
在模型上,如下所示 IDataErrorInfo 索引器被触发。
class EmailSettingsModel
{
public string SmtpServer
{ get; set; }
}
没有调用 IDataErrorInfo 是因为我为绑定(bind)语句使用了复合属性。我已经将这样的复杂属性用于普通数据绑定(bind)并且它们可以工作,但是对于这个示例,没有调用 IDataErrorInfo。
最佳答案
IDataErrorInfo 仅在实现的级别触发
例如,如果您的绑定(bind)路径类似于“viewModel.property1.property2.property3”,则需要在 viewModel 类、property1 类和 property2 类中实现 IDataErrorInfo。 Property3 是一个字符串。
所以为了让它为你工作,只需在其他任何地方实现 IDataErrorInfo 。
关于wpf - 绑定(bind)到复杂对象时不会触发 IDataErrorInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20012753/