Bind to IDataErrorInfo : Binding « Windows Presentation Foundation « C# / C Sharp






Bind to IDataErrorInfo

  

<Window
    x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF" Height="136" Width="260">

    <Window.Resources>
        <Style 
            x:Key="textBoxInErrorStyle" 
            TargetType="{x:Type TextBox}" >
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self},Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel DockPanel.Dock="Right">
                            <AdornedElementPlaceholder/>
                            <Image Source="Error.png" Width="16" Height="16" ToolTip="{Binding Path=AdornedElement.ToolTip, 
                                         RelativeSource={RelativeSource 
                                            Mode=FindAncestor,
                                            AncestorType={x:Type Adorner}}}"/>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

    </Window.Resources>

    <StackPanel>
        <TextBlock Text="First Name"/>
        <TextBox Style="{StaticResource textBoxInErrorStyle}" Text="{Binding Path=FirstName, Mode=TwoWay,
                           UpdateSourceTrigger=PropertyChanged,
                           ValidatesOnDataErrors=True}" />
        
        <TextBlock Text="Age" Grid.Row="2" VerticalAlignment="Center"/>
        <TextBox Style="{StaticResource textBoxInErrorStyle}"
            Margin="4" Text="{Binding Path=Age, Mode=TwoWay,        
                           UpdateSourceTrigger=PropertyChanged,
                           ValidatesOnDataErrors=True}"/>
        
    </StackPanel>
</Window>
//File:Window.xaml.cs
using System.Windows;
using System.ComponentModel;
namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            this.DataContext = new Employee(){FirstName = "A",Age = 26,};
        }
    }

    public class Employee : INotifyPropertyChanged,IDataErrorInfo
    {
        private string firstName;
        private int age;

        public Employee()
        {
            FirstName = "A";
        }
        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                if(firstName != value)
                {
                    firstName = value;
                    OnPropertyChanged("FirstName");
                }
            }
        }

        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                if(this.age != value)
                {
                    this.age = value;
                    OnPropertyChanged("Age");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName){
            if(this.PropertyChanged != null)
            {
                this.PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
            }
        }
        public string Error
        {
            get
            {
                return string.Empty;
            }
        }

        public string this[string propertyName]
        {
            get
            {
                string message = string.Empty;

                switch(propertyName)
                {
                    case "FirstName":
                        if(string.IsNullOrEmpty(firstName))
                            message = "A person must have a first name.";
                        break;

                    case "Age":
                        if(age < 1)
                            message = "A person must have an age.";
                        break;

                    default:
                        break;
                }

                return message;
            }
        }
    }
}

   
    
  








Related examples in the same category

1.Bind property of one instantiated controlBind property of one instantiated control
2.Bind to Window itselfBind to Window itself
3.Two level path bindingTwo level path binding
4.Bind RelativeSource's AncestorTypeBind RelativeSource's AncestorType
5.Bind RelativeSource's AncestorType's PathBind RelativeSource's AncestorType's Path
6.Bind Stroke Thickness to SliderBind Stroke Thickness to Slider
7.Bind current time to ButtonBind current time to Button
8.Desktop to ControlDesktop to Control
9.Bind Label To ScrollBarBind Label To ScrollBar
10.Bind ScrollBar To LabelBind ScrollBar To Label
11.Binding With Data ContextBinding With Data Context
12.Long Binding PathLong Binding Path
13.Bind ListBox ItemsSource to DayNames property of DateTimeFormatInfoBind ListBox ItemsSource to DayNames property of DateTimeFormatInfo
14.Bind TextBlock Text to SelectedItem property of ListBoxBind TextBlock Text to SelectedItem property of ListBox
15.Bind To TextBox Back and ForthBind To TextBox Back and Forth
16.Binding FontFamily / FontSize value for current ControlBinding FontFamily / FontSize value for current Control
17.Bind to a Collection with the Master-Detail PatternBind to a Collection with the Master-Detail Pattern
18.Bind to a collectionBind to a collection
19.DataTemplate for bindingDataTemplate for binding
20.Binding Environment InfoBinding Environment Info
21.Bind to an ADO.NETDataSetBind to an ADO.NETDataSet
22.Add a value converter to a binding using XAMLAdd a value converter to a binding using XAML
23.Custom Dialog with data binding
24.One way and two way bindingOne way and two way binding
25.Object BindingObject Binding
26.Without BindingWithout Binding
27.Master Detail BindingMaster Detail Binding
28.Data binding using collections composed of mixed types of data.Data binding using collections composed of mixed types of data.
29.Text Data BindingText Data Binding
30.List BindingList Binding
31.Async bindingAsync binding
32.Null property bindingNull property binding
33.Binding Property with ExceptionBinding Property with Exception
34.Hierarchical Binding for three level nested objectsHierarchical Binding for three level nested objects
35.BindingOperations.GetBindingExpressionBindingOperations.GetBindingExpression
36.Collection View Source BindingCollection View Source Binding
37.Bind to enum typesBind to enum types
38.Bind to a MethodBind to a Method
39.Bind an ItemsControl to the CollectionViewSource, Set its DisplayMemberPath to display the Name propertyBind an ItemsControl to the CollectionViewSource, Set its DisplayMemberPath to display the Name property
40.Bind to the Values of an EnumerationBind to the Values of an Enumeration
41.Binding Dependency Property to TextBlockBinding Dependency Property to TextBlock
42.Bind Your Objects to UI Control with PropertyBind Your Objects to UI Control with Property
43.Implement INotifyPropertyChanged to notify the binding targets when the values of properties change.Implement INotifyPropertyChanged to notify the binding targets when the values of properties change.
44.Bind to an Existing Object InstanceBind to an Existing Object Instance
45.Digital ClockDigital Clock
46.Formatted Digital ClockFormatted Digital Clock
47.Manual Update TargetManual Update Target
48.Property changed callbackProperty changed callback