0

当我在 DataGrid 的行中输入错误时,我想通知验证错误。

<DataGridTextColumn Header="Name" Binding="{Binding Path=Name, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/>
<DataGridTextColumn Header="Age" Binding="{Binding Path=Age}"/>
<DataGridTextColumn Header="Date Of Birth" Binding="{Binding Path=DateOfBirth, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, NotifyOnValidationError=True}"/>

我使用以下属性在 ViewModel 中实现了 IDataErrorInfo。

public string this[string propname]
        {
            get 
            {
                switch (propname)
                {
                    case "Age":
                        int age=0;
                        if (int.TryParse("Age", out age))
                        {
                            if (age <= 0 && age > 99)
                            {
                                return "Please enter the valid Age...";
                            }
                        }
                        else
                            return "Please enter the valid Age...";

                        break;
                    case "Name":
                        if (string.IsNullOrEmpty("Name"))
                        {
                            return "Enter the valid Name";
                        }
                        break;
                    case "Address":
                        if (string.IsNullOrEmpty("Address"))
                        {
                            return "Enter the valid Address";
                        }
                        break;
                    case "DateOfBirth":
                        DateTime datetime;
                        if (!DateTime.TryParse("DateOfBirth", out datetime))
                        {
                            return "Please enter the valid Date of Birth";
                        }
                        break;
                }
                return string.Empty;
            }
        }

但是验证没有发生。我需要这样的要求,如果我在 DataGridCell 中的 DateTime 属性中键入文本,则应该有红色气球来指示验证错误。

有可能吗?..有人吗?

4

1 回答 1

2

这一行:

if (int.TryParse("Age", out age))

不可能是正确的。

如果您想要一个红色气球出现,您需要提供红色气球:

<Style x:Key="TextBlockStyle" 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>

和:

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <TextBlock Style="{StaticResource ResourceKey=TextBlockStyle}" 
                   Text="{Binding Path=Name,  UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

我把它留给你让它变红。

于 2012-05-15T14:15:13.317 回答