Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

IDataErrorInfo Interface

Defines members that data entity classes can implement to provide custom validation support.

Namespace:  System.ComponentModel
Assembly:  System (in System.dll)

[DefaultMemberAttribute("Item")]
public interface IDataErrorInfo

The IDataErrorInfo type exposes the following members.

  NameDescription
Public propertySupported by Silverlight for Windows PhoneErrorGets a message that describes any validation errors for the object.
Public propertySupported by Silverlight for Windows PhoneItemGets a message that describes any validation errors for the specified property or column name.
Top

This interface enables data entity classes to implement custom validation rules and expose validation results to the user interface. You typically implement this interface to provide relatively simple, client-side validation logic.

To provide asynchronous or server-side validation logic, implement the INotifyDataErrorInfo interface instead.

In general, new entity classes for Silverlight should implement INotifyDataErrorInfo for the added flexibility instead of implementing IDataErrorInfo. The IDataErrorInfo support enables you to use many existing entity classes that are written for the full .NET Framework. Other validation options are also available, such as the use of data attributes. For more information, see Data Binding.

IDataErrorInfo Members

The IDataErrorInfo.Item property returns a single validation error message. The Error property returns a single error message for the entire object. Each of these single messages can represent multiple errors. If you want to represent multiple errors by using multiple custom error objects, implement the INotifyDataErrorInfo interface instead. This enables more detailed error reporting in the user interface (UI).

Data Binding Support

The Silverlight binding engine provides built-in support for IDataErrorInfo. To enable this support, bind a control to a property of an entity that implements IDataErrorInfo, and set the Binding.ValidatesOnDataErrors property to true. Then, whenever a bound entity property changes value, the binding engine validates the new value by passing the property name to IDataErrorInfo.Item. Note that the binding engine never uses the Error property, although you can use it in custom error reporting to display object-level errors.

The binding engine uses the validation results to update the Validation.Errors collection for that binding. First, the binding engine removes any existing errors for the bound property that originate from exceptions or from IDataErrorInfo validation. Then, if the new value is not valid, the binding engine adds a new error for the property.

You can use ValidatesOnExceptions and ValidatesOnDataErrors at the same time; however, any exceptions that occur will prevent IDataErrorInfo validation.

Error Reporting

The Validation.Errors collection provides a binding source for error reporting in the user interface. Several controls bind to this collection from their default control templates.

To provide custom error reporting, you can replace the default templates with customized versions. For more information, see Control Customization. You can also set the Binding.NotifyOnValidationError property to true and handle the FrameworkElement.BindingValidationError event. This event occurs each time an error is added or removed for a particular binding. Some controls, such as ValidationSummary, require this mechanism instead of using the Validation.Errors collection.

The following example code demonstrates how to implement IDataErrorInfo. This example uses the same error reporting structure as the example for the INotifyDataErrorInfo interface. However, in the IDataErrorInfo implementation, multiple errors for a single property are combined into a single error message. This limits the options for custom error reporting. Additionally, the IDataErrorInfo interface does not support the future addition of asynchronous validation rules.


using System;
using System.ComponentModel;
using System.Collections.Generic;

namespace IDataErrorInfoExample
{

    public class Product : IDataErrorInfo
    {
        private int idValue;

        public int Id
        {
            get { return idValue; }
            set { if (IsIdValid(value) && idValue != value) idValue = value; }
        }

        private string nameValue;
        public string Name
        {
            get { return nameValue; }
            set { if (IsNameValid(value) && nameValue != value) nameValue = value; }
        }

        // Validates the Id property, updating the errors collection as needed.
        public bool IsIdValid(int value)
        {
            bool isValid = true;

            if (value < 5)
            {
                AddError("Id", ID_ERROR, false);
                isValid = false;
            }
            else RemoveError("Id", ID_ERROR);

            if (value < 10) AddError("Id", ID_WARNING, true);
            else RemoveError("Id", ID_WARNING);

            return isValid;
        }

        // Validates the Name property, updating the errors collection as needed.
        public bool IsNameValid(string value)
        {
            bool isValid = true;

            if (value.Contains(" "))
            {
                AddError("Name", NAME_ERROR, false);
                isValid = false;
            }
            else RemoveError("Name", NAME_ERROR);

            if (value.Length > 5) AddError("Name", NAME_WARNING, true);
            else RemoveError("Name", NAME_WARNING);

            return isValid;
        }

        private Dictionary<String, List<String>> errors =
            new Dictionary<string, List<string>>();
        private const string ID_ERROR = "Value cannot be less than 5.";
        private const string ID_WARNING = "Value should not be less than 10.";
        private const string NAME_ERROR = "Value must not contain any spaces.";
        private const string NAME_WARNING = "Value should be 5 characters or less.";

        // Adds the specified error to the errors collection if it is not already 
        // present, inserting it in the first position if isWarning is false. 
        public void AddError(string propertyName, string error, bool isWarning)
        {
            if (!errors.ContainsKey(propertyName))
                errors[propertyName] = new List<string>();

            if (!errors[propertyName].Contains(error))
            {
                if (isWarning) errors[propertyName].Add(error);
                else errors[propertyName].Insert(0, error);
            }
        }

        // Removes the specified error from the errors collection if it is present. 
        public void RemoveError(string propertyName, string error)
        {
            if (errors.ContainsKey(propertyName) &&
                errors[propertyName].Contains(error))
            {
                errors[propertyName].Remove(error);
                if (errors[propertyName].Count == 0) errors.Remove(propertyName);
            }
        }

        #region IDataErrorInfo Members

        public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string propertyName]
        {
            get
            {
                return (!errors.ContainsKey(propertyName) ? null :
                    String.Join(Environment.NewLine, errors[propertyName]));
            }
        }

        #endregion
    }
}



<UserControl x:Class="IDataErrorInfoExample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

  <Grid x:Name="LayoutRoot" Background="White" Margin="10">

    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto"/>
      <ColumnDefinition Width="200"/>
      <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <TextBlock Grid.Column="1" Margin="3" Text="Product" FontWeight="Bold"/>

    <sdk:Label Grid.Row="1" Target="{Binding ElementName=IdTextBox}" 
      Margin="3" HorizontalAlignment="Right"/>
    <TextBox x:Name="IdTextBox" KeyDown="TextBox_KeyDown"
      Grid.Column="1" Grid.Row="1" Margin="3" MaxLength="5" 
      Text="{Binding Id, Mode=TwoWay, ValidatesOnExceptions=True,
      ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>
    <sdk:DescriptionViewer Grid.Column="2" Grid.Row="1" 
      Description="Id must be greater than 4 and should be greater than 9."/>

    <sdk:Label Grid.Row="2" Target="{Binding ElementName=NameTextBox}" 
      Margin="3" HorizontalAlignment="Right"/>
    <TextBox x:Name="NameTextBox" KeyDown="TextBox_KeyDown"  
      Grid.Column="1" Grid.Row="2" Margin="3" MaxLength="10" 
      Text="{Binding Name, Mode=TwoWay, ValidatesOnExceptions=True,
      ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>
    <sdk:DescriptionViewer Grid.Column="2" Grid.Row="2" Description=
      "Name must not contain spaces and should be 5 characters or less."/>

    <sdk:ValidationSummary Grid.Row="3" Grid.ColumnSpan="2" Margin="3"/>

  </Grid>
</UserControl>



using System.Windows.Controls;

namespace IDataErrorInfoExample
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            LayoutRoot.DataContext = new Product() { Id = 10, Name = "food" };
        }

        // Commits text box values when the user presses ENTER. This makes it 
        // easier to experiment with different values in the text boxes.
        private void TextBox_KeyDown(object sender,
            System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter) (sender as TextBox)
                .GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }
    }
}


Silverlight

Supported in: 5, 4

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft