0

I have a class called Person and a List called People, show below:

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public List<Person> People;

        public MainWindow()
        {
            InitializeComponent();

            People = new List<Person>();
            People.Add(new Person() { ID = 1, Name = "John" });
            People.Add(new Person() { ID = 2, Name = "Mike" });
        }
    }

    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

And I want to display the 2 Person in People to an DataGrid, using a combobox to choose between the 2 Person.

<DataGrid x:Name="dataGrid1" Height="300">
    <DataGridComboBoxColumn Header="Name" DisplayMemberPath="Name" SelectedItemBinding="{Binding Path=Name}">
        <DataGridComboBoxColumn.EditingElementStyle>
            <Style TargetType="ComboBox">
                <Setter Property="ItemsSource" Value="{Binding Path=People}"/>
            </Style>
        </DataGridComboBoxColumn.EditingElementStyle>
        <DataGridComboBoxColumn.ElementStyle>
            <Style TargetType="ComboBox">
                <Setter Property="ItemsSource" Value="{Binding Path=People}"/>
            </Style>
        </DataGridComboBoxColumn.ElementStyle>
    </DataGridComboBoxColumn>
</DataGrid>

But the DataGrid just display nothing at all. What's the problem?

Senhtry
  • 1
  • 2

2 Answers2

0

Shouldnt it be inside a <DataGrid.Columns> tag?

Koen
  • 634
  • 3
  • 14
  • It does provide a partial answer, in that the author's code won't work until the column definition is wrapped in ``, but there are other issues as well. – Mike Strobel Oct 28 '14 at 14:00
0
  1. People must be a property, not a field.
  2. You must populate the collection before assigning it to People, or you must replace the list with an ObservableCollection<Person> so the grid will detect the items you've added.
  3. You must assign People before the call to InitializeComponent(), or the class containing the property must implement INotifyPropertyChanged and fire the PropertyChanged when People is assigned so the grid detects the new collection.
  4. As @Koen points out, your column definitions must be collectively surrounded by a <DataGrid.Columns> tag.
Mike Strobel
  • 25,075
  • 57
  • 69