简体   繁体   中英

Validation on DataGrid

I have a datagrid displaying ObservableCollection in my xaml. One of my validation rule on one of the columns is "Name cannot be blank" when the Name field is blank. It all works fine.

My problem is that when my Name field validation is triggered (if name was blank), the Name field is outlined with red box. Imagine at this stage the user fills in a name but the red box still remains even if you click on the other fields of the same row. The red box goes away only when the user clicks on a different row. Is there any way to make the red box disappear when the user click on different fields of the same row?

My xaml for the Name field is

<Window.Resources>
    <Style x:Key="EditCellStyleError" 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}"/>
        </Trigger>
    </Style.Triggers>
    </Style>
    <Style x:Key="CellStyleError" TargetType="{x:Type TextBlock}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

The Name field

<DataGridTextColumn Header="Name" Binding="{Binding Name,ValidatesOnDataErrors=True, NotifyOnValidationError=True, ValidatesOnExceptions=True}" EditingElementStyle="{StaticResource EditCellStyleError}" ElementStyle="{StaticResource CellStyleError}"/>

I think you need to add UpdateSourceTrigger to your binding

eg

<DataGridTextColumn Header="Name" 
  Binding="{Binding Name,ValidatesOnDataErrors=True, NotifyOnValidationError=True,
  ValidatesOnExceptions=True,  UpdateSourceTrigger=LostFocus}" />

here Ive used LostFocus but PropertyChanged might be an option

UpdateSourceTrigger=PropertyChanged definitely helped. Another problem was to get rid of red exclamation mark. To achieve this I added a blank Rowvalidationtemplate

        <DataGrid.RowValidationErrorTemplate>
            <ControlTemplate>
            </ControlTemplate>
        </DataGrid.RowValidationErrorTemplate>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM