Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用实体框架在WPF MVVM中进行验证_C#_Wpf_Entity Framework_Validation_Mvvm - Fatal编程技术网

C# 使用实体框架在WPF MVVM中进行验证

C# 使用实体框架在WPF MVVM中进行验证,c#,wpf,entity-framework,validation,mvvm,C#,Wpf,Entity Framework,Validation,Mvvm,我正在使用Visual Studio 2015编写WPF MVVM Light应用程序。数据是使用Entity Framework 6引入的,首先使用数据库生成模型。在MainViewModel.cs文件中,我希望在执行SaveChanges()之前验证数据 我看到的例子谈到了向模型添加注释(例如,);但是,我使用的是自动生成的实体框架模型。而我的ViewModels引用了ObservableCollection对象——没有任何对象直接引用字段,因此我可以在字段上添加注释 下面是SearchRe

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

我看到的例子谈到了向模型添加注释(例如,);但是,我使用的是自动生成的实体框架模型。而我的ViewModels引用了
ObservableCollection
对象——没有任何对象直接引用字段,因此我可以在字段上添加注释

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

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

        _searchResults = value;
        RaisePropertyChanged("SearchResults");
    }
}
用户单击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
,而
firstName
lastName
是必需的,等等。如何完成此验证并向用户显示错误

我假设当您向用户显示您正在使用的
TextBox
es的详细信息时(您可以对其他控件应用相同的解决方案)

用户更改
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>

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

谢谢,@qqww2。如何在正在验证的字段旁边显示错误消息?请查找
Validation.ErrorTemplate
。这是一个好看的。
<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;
    }
}