如何从位于ObservableCollection <t>内的属性List <t>填充DataGridComboBoxColumn? MVVM

时间:2015-09-15 11:04:17

标签: c# wpf mvvm datagrid datagridcomboboxcolumn

我的视图模型类中有一个属性ObservableCollection SomeEmployee:

private ObservableCollection<Employee> someEmployee=new ObservableCollection<Employee>();
public ObservableCollection<Employee> SomeEmployee 
{
 get {return someEmployee;}
  set { 
       someEmployee=value;
       OnPropertyChanged("SomeEmployee");
}

Somempmployee由PopulateObject()方法填充

public static IEnumerable<Employee> PopulateObject()
    {
        IEnumerable<Employee> list = new List<Employee>() 
        {
             new Employee { EmployeeName = "Bob", EmployeeID=1,
                  ListOfEmployees=new List<Employee>(){
                      new Employee(){EmployeeName="Gigi"}, 
                      new Employee(){EmployeeName="Bacconi"} 
                      new Employee(){EmployeeName="Teodor"} }
                          },
             new Employee { EmployeeName = "John", EmployeeID=2, },
             new Employee { EmployeeName = "Adam", EmployeeID=3, }, 
        };
        return list;
    }

Employee类有一个属性ListOfEmployees,我想在DataGrid的DataGridComboBoxColumn中显示:

public class Employee 
{
   public int? EmployeeID {get; set;}
   public string EmployeeName {get; set;}
   public List<Employee> ListOfEmployees {get; set;}

我的DataGrid:

<DataGrid ItemsSource="{SomeEmployee}">
 <DataGrid.Columns>
     <DataGridComboBoxColumn Header="ComboBox" SelectedItemBinding="{Binding EmployeeName}">
      <DataGridComboBoxColumn.ElementStyle>
  <Style TargetType="ComboBox">
     <Setter Property="ItemsSource" Value="Binding Path=DataContext.ListOfEmployees}"/>
  </Style>
   </DataGridComboBoxColumn.ElementStyle>
  </DataGridComboBoxColumn>
   </DataGrid.Columns>
   </DataGrid>

但是,首先没有显示ComboBox,它就像显示简单的DataGridTextColumn一样。第二,单元格中没有数据。

如何从位于ObservableCollection内的属性列表中填充DataGridComboBoxColumn ?我做错了什么?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您不需要在样式中设置ItemsSource,您可以执行以下操作:

 <DataGrid ItemsSource="{SomeEmployee}">
   <DataGrid.Columns>
     <DataGridComboBoxColumn Header="ComboBox" SelectedItemBinding=" {Binding EmployeeName}" ItemSource="{Binding EmployeeID}">
     </DataGridComboBoxColumn>
   </DataGrid.Columns>
 </DataGrid>
您的模型中不存在

ListOfEmployees,我想您要绑定到EmployeeID

答案 1 :(得分:0)

表达式

ObservableCollection<Employee> SomeEmployee =
    new ObservableCollection<Employee>(PopulateObject());

不会声明属性,而是声明字段。例如,属性可能如下所示:

// backing field
private ObservableCollection<Employee> someEmployee =
    new ObservableCollection<Employee>(PopulateObject());

// property
public ObservableCollection<Employee> SomeEmployee
{
    get { return someEmployee; }
}

现在您将在XAML中绑定该属性。而不是

<DataGrid ItemsSource="{SomeEmployee}">
你会写

<DataGrid ItemsSource="{Binding SomeEmployee}">

这还要求声明属性的视图模型类的实例(以及您未在问题中显示的)被分配给DataGrid的DataContext或其父控件之一:

DataContext = new ViewModel();