Click here to Skip to main content
15,889,200 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
My class, which implements IDataErrorInfo, returns error message such way:
<pre lang="cs">public string Error
            {
                get
                {
                    StringBuilder sb = new StringBuilder();
                    if (NameOfWear.Length > 5 && Convert.ToInt16(Price) < 20000)
                    return sb.Append("Price is too small").ToString();
                    return sb.ToString();
                }
               }


This error is updated only at the start of application, or when I sort items in dataGrid, or when i call GridComponent.Reset(something like that). But I change this elemet from another textbox, both elements are binded . When I change textbox, element of dataGrid automatically changes too, and simle exceptions work onPropertyChanges and CollectionChanes,such as:
<pre lang="cs">public string this[string columnName]
               {
                   get
                   {
                       string result = "";
                       int i;
                       if (columnName == "NameOfWear")
                       {
                           if (string.IsNullOrWhiteSpace(NameOfWear))
                           {
                               result = "Enter any name";
                           }
                           else if (NameOfWear.Length < 3)
                           {
                               result = "Correct name plz";
                           }
                           else if(int.TryParse(NameOfWear,out i))
                           {
                               result="No numbers";
                           }
                       }
                       else if (columnName == "Price")
                       {
                           if (!int.TryParse(Price, out i))
                           {
                               result = "Only numbers";
                           }
                       }
                       return result;




How to make this exception to be displayed on PropertyChanged, not when GridReset,etc?
P.S. MY XAML:
<<pre lang="xml">Page x:Class="WpfBrowserApplication1.Page1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:WpfBrowserApplication1"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="307"
      Title="Page1">
    <Page.Resources>
        <Style x:Key="ErrorStyle" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
                    <Setter Property="BorderThickness" Value="0"/>
                    <Setter Property="Padding" Value="0"/>
                </Trigger>
            </Style.Triggers>
        </Style>
        <Style x:Key="RowStyle" TargetType="{x:Type DataGridRow}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="BorderThickness" Value="1"/>
                    <Setter Property="BorderBrush" Value="Red"/>
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Page.Resources>
    <Grid>
        <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel  >
            <TextBox Margin="3" IsReadOnly="True">Название</TextBox>
            <TextBox Style="{StaticResource ResourceKey=ErrorStyle}" Margin="3"  Text="{Binding Path=wear.NameOfWear, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"  ></TextBox>
            <TextBox Margin="3" IsReadOnly="True" >Цена</TextBox >
            <TextBox Style="{StaticResource ResourceKey=ErrorStyle}" Margin="3" Text="{Binding Path=wear.Price, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"></TextBox>
            <StackPanel Orientation="Horizontal">
                <Button HorizontalAlignment="Stretch" Margin="3" Command="{Binding Path=AddRowCommand}" >Добавить поле</Button>
                <Button HorizontalAlignment="Stretch" Margin="3" Command="{Binding Path=RemoveRowCommand}" Content="RemoveRow"></Button>
            </StackPanel>
        </StackPanel>
        <DataGrid  RowStyle="{StaticResource RowStyle}"  ItemsSource="{Binding Path=Collection, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"  SelectedItem="{Binding Path=wear, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" IsSynchronizedWithCurrentItem="True" AutoGenerateColumns="False" HorizontalAlignment="Stretch"  Name="dataGrid1" VerticalAlignment="Stretch" IsReadOnly="False" Grid.Row="1">
            <DataGrid.RowValidationRules>
                <DataErrorValidationRule ValidationStep="UpdatedValue"  ValidatesOnTargetUpdated="True">
                </DataErrorValidationRule>
            </DataGrid.RowValidationRules>
            <DataGrid.Columns >
                <DataGridTextColumn  Header="Name" Binding="{Binding Path=NameOfWear, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Width="*"></DataGridTextColumn>
                <DataGridTextColumn  Header="Price" Binding="{Binding Path=Price, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Width="*"></DataGridTextColumn>
                </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Page>


P.S.2 Everything works fine,except this.
P.S.3 Sorry for bad English /
Posted

I wrote an article on validating user input using IDataErrorInfo Here[^]. This shows how to validate at the property level like you want I think.

Hope this helps
 
Share this answer
 
Comments
Tonven 20-Apr-11 10:41am    
I read your article, but I have a bit another problem , when I need to have a rule, which involves several properties(for example, if u tell that u was born in London but not in England i need to display exception). I can do this, but only at the start of application, or when u sort DataGrid, because all this iitems are stored in DG.
I have explained the use of IDataErrorInfo in my blog here : http://tarundotnet.wordpress.com/2011/03/03/wpf-tutorial-how-to-use-idataerrorinfo-in-wpf/[^]
It also has a custom validation rule used in a different class for trapping more exceptions and adding your own rules.
 
Share this answer
 
v2
Comments
Tonven 20-Apr-11 10:48am    
As I said, I work with DataGrid, update it from another textbox. And I need to work not only with properties, but with complex errors, and I should see mistakes when property changes.
Tarun.K.S 20-Apr-11 10:50am    
I'm not sure about DataGrid but it does show the errors and displays it as ToolTip whenever the property changes.
Tonven 20-Apr-11 13:06pm    
And how to show this Tooltip for both fields, the property I changed and the property from what it depends?( in your example for weith and heith so make red both fields on propertychange of ONLY one?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900