2016-12-24 70 views
0

Trynig到的DataContext设置为WPF窗口我使用CodeFirst这里是代码WPF窗口的DataContext错误“无效列名”

public class Employee 
{ 
    [Key] 
    public int EmployeeId { get; set; } 

    [Display(Name = "FullName")] 
    [Required(ErrorMessage = "FullNameRequired")] 
    public string FullName { get; set; } 

    public string Address { get; set; } 

    public string Phone { get; set; } 

    public double Salary { get; set; } 

    public string Email { get; set; } 

    public string Job { get; set; } 

} 

public class EmployeeVM 
{ 
    SDBContext db = new SDBContext(); 

    public List<Employee> Employees; 

    public EmployeeVM() 
    { 
     this.Employees= db.Employees.ToList(); 
    } 
} 

添加视图模型到窗口的DataContext

xmlns:VM="clr-namespace:Project_Test.ViewModels" 

<Window.DataContext> 
    <VM:EmployeeVM/> 
</Window.DataContext> 

但我得到错误“无效的列名作业”

和我试图绑定'员工'收集到DataGrid,但它没有工作

ItemsSource="{Binding Employees}" 

完成,在隐藏代码,它工作正常

SDBContext db = new SDBContext(); 
public MainWindow() 
{ 
    InitializeComponent(); 

    DG_Employees.ItemsSource = db.Employees.ToList(); 
} 

更新

我删除属性“工作”,并得到了另一个错误: “的模式支持背景自上改变数据库已创建。考虑使用代码第一”

回答

0

如果您第一次的工作方式,你Employees必须是财产,不是野外,像这样:

public class EmployeeVM 
{ 
    SDBContext db = new SDBContext(); 

    public List<Employee> Employees {get;set;} 

    public EmployeeVM() 
    { 
     this.Employees= db.Employees.ToList(); 
    } 
} 

然后,当您绑定的ItemsSource你的员工就应该工作

不过。

如果计划装载员工从数据库除了costructor的地方,你EmployeeVMshould implement INotifyPropertyChangedEmployees属性应该提高PropertyChanged事件上的变化,所以你的视图模型应该是这样的:

public class EmployeeVM : INotifyPropertyChanged 
{ 
    SDBContext db = new SDBContext(); 

    private List<Employee> _employees; 
    public List<Employee> Employees 
    { 
     get { return _employees; } 
     set 
     { 
      if (Equals(value, _employees)) return; 
      _employees = value; 
      OnPropertyChanged("Employees"); 
     } 
    } 

    public EmployeeVM() 
    { 
     this.Employees = db.Employees.ToList(); 
    } 


    public event PropertyChangedEventHandler PropertyChanged; 

    [NotifyPropertyChangedInvocator] 
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     var handler = PropertyChanged; 
     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

然后,每次你做你的this.Employees = /..something../绑定的DataGrid中应该看到的ItemsSource时间而改变。

但甚至更多,如果你打算让用户添加/ DataGrid中删除Employees或以其他方式修改Employees集合,你应该改变从List<Employee>Employees物业类型ObservableCollection<Employee>,然后你的视图(如DataGrid中)应该得到每当新员工将被移除或添加到Employees集合时发生的事件。

还有更多,如果你打算改变像FullName等员工的属性,并希望可以通过视图注意到这些变化(如DataGrid中更新对应Eployee的FullName后的细胞被改变)你的Employee类,反过来,应执行INotifyPropertyChanged太 - 但更好的是,你更不用说Employee,它是Model的一部分,并从数据库加载并为Employee类创建单独的视图模型。

我必须添加,如果你的任务只是在ViewModel构造中只加载来自数据库的员工,让他们查看,只读,没有版本,更新或删除,你可以省略上面所有的麻烦,但我认为这是一种罕见的情况。