Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDataErrorInfo does not fire when binding to a complex object

Tags:

wpf

I have a simple dialog that contains edit boxes such as this:

<TextBox Text="{Binding Path=EmailSettings.SmtpServer, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" />

The dialog uses a Model as its data context (to simplify the model example INotifyPropertyChanged has not been shown nor is the code that creates the model and sets the dialog data context to the model instance):

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;
         }
     }
}

The model contains a property that is a simple POCO class that has several properties on it.

class EmailSettings
{
   public string SmtpServer
   { get; set; } 
}

I could not get the IDataErrorInfo indexer to fire and spent hours looking. When I changed the binding on the text box to use a simple property:

<TextBox Text="{Binding Path=SmtpServer, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" />

on the Model as below the IDataErrorInfo indexer fired.

class EmailSettingsModel
{
   public string SmtpServer
   { get; set; } 
}

Was IDataErrorInfo not called because I used a compound property for the binding statement. I have used complex properties like this for normal data binding and they work but for this example IDataErrorInfo was not called.

like image 432
dgxhubbard Avatar asked Nov 15 '13 23:11

dgxhubbard


1 Answers

IDataErrorInfo fires only at the level where implemented

For example if you have Binding Path looking like this "viewModel.property1.property2.property3" you will need to implement IDataErrorInfo inside the class of viewModel and inside the class of property1 and inside the class of property2. Property3 is a string.

So in order to make it work for you just implement IDataErrorInfo anywhere else.

like image 57
dev hedgehog Avatar answered Sep 21 '22 12:09

dev hedgehog