【问题标题】:Validation in WPF MVVM with Entity Framework使用实体框架在 WPF MVVM 中进行验证
【发布时间】:2016-07-04 10:37:20
【问题描述】:

我正在使用 Visual Studio 2015 编写 WPF MVVM Light 应用程序。数据已使用 Entity Framework 6 引入,并使用数据库优先来生成模型。在我的 MainViewModel.cs 文件中,我想在执行 SaveChanges() 之前验证数据。

我见过的例子都在谈论为模型添加注释(例如,this);但是,我使用的是自动生成的实体框架模型。而且我的 ViewModel 引用了 ObservableCollection<Employee> 对象——没有任何东西直接引用字段,所以我可以在它们上添加注释。

这里是SearchResults 属性,它保存从 EF 返回的结果:

private ObservableCollection<Employee> _searchResults;
public ObservableCollection<Employee> SearchResults
{
    get { return _searchResults; }
    set
    {
        if (_searchResults == value) return;

        _searchResults = value;
        RaisePropertyChanged("SearchResults");
    }
}

SearchResults 在搜索后填充并绑定到 DataGrid:

var query = Context.Employees.AsQueryable();

// Build query here...

SearchResults = new ObservableCollection<Employee>(query.ToList());

用户单击 DataGrid 上的一行,我们会显示详细信息以供他们更新。然后他们可以点击保存按钮。但是我们想在执行Context.SaveChanges() 之前验证每个Employee 中的字段。

这是由实体框架自动生成的部分类Employee 的相关区域:

public int employeeID { get; set; }
public int securityID { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public string suffix { get; set; }
public string job { get; set; }
public string organizationalUnit { get; set; }
public string costCenter { get; set; }
public string notes { get; set; }
public System.DateTime createdDate { get; set; }

例如,securityID 不能为空且必须为int,而firstNamelastName 是必需的,等等。您如何完成此验证并向用户显示错误?

【问题讨论】:

    标签: c# wpf entity-framework validation mvvm


    【解决方案1】:

    我假设当您向用户展示您正在使用的详细信息 TextBoxes(您可以将相同的解决方案应用于其他控件)。

    不要在用户更改Employee的属性后验证数据,只需预先验证,如果属性无效,甚至不要更改属性。

    您可以使用ValidationRule 类轻松完成此操作。例如:

    <ListBox ItemsSource="{Binding Employees}" Name="ListBoxEmployees">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"></TextBlock>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <TextBox>
        <TextBox.Text>
            <Binding ElementName="ListBoxEmployees" Path="SelectedItem.Name" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <stackOverflow:NotEmptyStringValidationRule/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
    

    和验证规则:

    public class NotEmptyStringValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            string s = value as string;
            if (String.IsNullOrEmpty(s))
            {
                return new ValidationResult(false, "Field cannot be empty.");
            }
    
            return ValidationResult.ValidResult;
        }
    }
    

    您还可以在任何验证规则失败时禁用“保存”按钮。

    【讨论】:

    • 谢谢@qqww2。如何在正在验证的字段旁边显示错误消息?
    • 寻找Validation.ErrorTemplateHere 挺好看的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多