c# - 如何在使用 IDataErrorInfo 时检查模型是否有效或有错误

这个问题可能很简单,但是我找不到办法做,所以我问了。

我在我的模型中使用 IDataErrorInfo 来验证它如下:

public class Group : INotifyPropertyChanged, IDataErrorInfo
{
    //Fileds & Properties

    public string Error
    {
        get { return String.Empty; }
    }

    public string this[string columnName]
    {
        get 
        {

            if (columnName == "GroupName")
            {
                bool _IsDuplicateGroupName;

                using (MunimPlusContext context = new MunimPlusContext())
                {
                    _IsDuplicateGroupName = context.GroupSet.Any(x => x.GroupName.ToLower() == GroupName.ToLower());
                }

                if (String.IsNullOrWhiteSpace(GroupName))
                {
                    return "Group Name cannot be Empty.";
                }
                else if (_IsDuplicateGroupName)
                {
                    return "Duplicate Group Name. Please choose a unique Group Name.";
                }
            }

            if (columnName == "ParentId")
            {
                if (ParentId == null)
                {
                    return "Please select Under Group under which " + (GroupName == null ? "this" : GroupName) + " Group will appear.";
                }
                else if (ParentId <= 0)
                {
                    return "Please select a valid GroupName from the list.";
                }
            }

            if (columnName == "NatureOfGroupId")
            {
                Group _PrimaryGroup;
                using (MunimPlusContext context = new MunimPlusContext())
                {
                    _PrimaryGroup = context.GroupSet.Where(x => x.GroupName == "Primary").FirstOrDefault();
                }

                if (_PrimaryGroup.GroupId == ParentId)
                {
                    if (NatureOfGroupId == null)
                    {
                        return "Please select the Nature of Group.";
                    }
                    else if (NatureOfGroupId <= 0)
                    {
                        return "Please select a valid Nature of Group from the list.";
                    }
                }
            }

            return String.Empty;
        }
    }
}

现在,在我的 XAML 中:

<Grid.Resources>
    <DataTemplate DataType="{x:Type ValidationError}">
        <TextBlock FontStyle="Italic" Foreground="Red" HorizontalAlignment="Right" Text="{Binding ErrorContent}" Margin="4,0,4,4" />
    </DataTemplate>
</Grid.Resources>

<TextBlock Grid.Row="3" Grid.Column="1" Text="Name" />
<TextBlock Grid.Row="3" Grid.Column="1" Text=":" />
<TextBox Grid.Row="3" Grid.Column="2" x:Name="txtGroupName" Text="{Binding GroupName, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>
<ContentPresenter Grid.Row="4" Grid.Column="2" Content="{Binding ElementName=txtGroupName, Path=(Validation.Errors).CurrentItem}" />

<TextBlock Grid.Row="5" Grid.Column="1" Text="Alias" />
<TextBlock Grid.Row="5" Grid.Column="1" Text=":" />
<TextBox Grid.Row="5" Grid.Column="2" x:Name="txtAlias" Text="{Binding Alias, ValidatesOnDataErrors=True}"/>
<ContentPresenter Grid.Row="6" Grid.Column="2" Content="{Binding ElementName=txtAlias, Path=(Validation.Errors).CurrentItem}" />

<TextBlock Grid.Row="7" Grid.Column="1" Text="Under" />
<TextBlock Grid.Row="7" Grid.Column="1" Text=":" />
<ComboBox Grid.Row="7" Grid.Column="2" x:Name="cmbParentGroup"
          ItemsSource="{DynamicResource Items}" SelectedValue="{Binding ParentId, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" 
          SelectedValuePath="Group.GroupId" Grid.IsSharedSizeScope="True" TextSearch.TextPath="Group.GroupName" LostFocus="cmbParentGroup_LostFocus"/>
<ContentPresenter Grid.Row="8" Grid.Column="2" Content="{Binding ElementName=cmbParentGroup, Path=(Validation.Errors).CurrentItem}" />

<TextBlock Grid.Row="9" Grid.Column="1" Text="Nature Of Group" />
<TextBlock Grid.Row="9" Grid.Column="1" Text=":" />
<ComboBox Grid.Row="9" Grid.Column="2" x:Name="cmbNatureOfGroup"
          ItemsSource="{Binding DataContext.NaturesOfGroup, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type core:UserControlViewBase}}}" 
          DisplayMemberPath="Nature" SelectedValue="{Binding NatureOfGroupId, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" 
          SelectedValuePath="NatureOfGroupId" LostFocus="cmbNatureOfGroup_LostFocus"/>
<ContentPresenter Grid.Row="10" Grid.Column="2" Content="{Binding ElementName=cmbNatureOfGroup, Path=(Validation.Errors).CurrentItem}" />

<StackPanel Grid.Row="11" Grid.Column="2" Orientation="Horizontal" HorizontalAlignment="Right">
    <Button Content="Save" Style="{StaticResource SaveButtonWithText}" 
            Command="{Binding DataContext.SaveCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type core:UserControlViewBase}}}"/>
    <Button Content="Cancel" Style="{StaticResource CancelButtonWithText}"
            Command="{Binding DataContext.CancelCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type core:UserControlViewBase}}}"/>
</StackPanel>

现在,当我将数据保存到数据库时,我想检查我的模型是否有效。我该怎么做?

最佳答案

终于从this得到了我的答案发布。

这是我的 IDataErrorInfo 实现代码:

public string Error
{
    get { return null; }
}

public string this[string propertyName]
{
    get { return GetValidationError(propertyName); }
}

private static readonly string[] ValidatedProperties = { "GroupName", "ParentId", "NatureOfGroupId" };

public bool IsValid
{
    get
    {
        foreach (string property in ValidatedProperties)
        {
            if (GetValidationError(property) != null)
            {
                return false;
            }
        }
        return true;
    }
}

private string GetValidationError(string propertyName)
{
    string error = null;

    switch (propertyName)
    {
        case "GroupName":

            bool _IsDuplicateGroupName;

            using (MunimPlusContext context = new MunimPlusContext())
            {
                _IsDuplicateGroupName = context.GroupSet.Any(x => x.GroupName.ToLower() == GroupName.ToLower());
            }

            if (String.IsNullOrWhiteSpace(GroupName))
            {
                error = "Group Name cannot be Empty.";
            }
            else if (_IsDuplicateGroupName)
            {
                error = "Duplicate Group Name. Please choose a unique Group Name.";
            }

            break;

        case "ParentId":

            if (ParentId == null)
            {
                error = "Please select Under Group under which " + (GroupName == null ? "this" : GroupName) + " Group will appear.";
            }
            else if (ParentId <= 0)
            {
                error = "Please select a valid GroupName from the list.";
            }

            break;

        case "NatureOfGroupId":

            Group _PrimaryGroup;
            using (MunimPlusContext context = new MunimPlusContext())
            {
                _PrimaryGroup = context.GroupSet.Where(x => x.GroupName == "Primary").FirstOrDefault();
            }

            if (_PrimaryGroup.GroupId == ParentId)
            {
                if (NatureOfGroupId == null)
                {
                    error = "Please select the Nature of Group.";
                }
                else if (NatureOfGroupId <= 0)
                {
                    error = "Please select a valid Nature of Group from the list.";
                }
            }

            break;

    }

    return error;

}

下面是我如何检查是否所有属性都对名为 CurrentGroup 的对象有效?

if (CurrentGroup.IsValid)
{
       //save data to the database.......
}

https://stackoverflow.com/questions/29356839/

相关文章:

php - 除页码外,删除 tcpdf 中的底线

amazon-web-services - 如何防止使用签名网址从亚马逊云端下载视频

ruby - 如何使 rake 任务依赖于文件和另一个任务

kdb - 从包含空格字符的路径加载 file.q

php - Doctrine ManyToMany 优化许多查询

r - dplyr:从 group_by 变量中删除 NA

r - 如何可视化概率分布函数之间的差异?

asp-classic - 检查请求是否来自本地主机

c# - RestSharp 缺少执行功能?

erlang - tlsv1 警告 rabbitmq 安全性不足