Ali
Ali

Reputation: 643

Fill DataGrid from a list of items

Actually, I have a small wpf application which have a DataGrid window that I could not fill it with objects.

In my ViewModel class I have this:

     public class UserViewModel : INotifyPropertyChanged
        {
            public UserViewModel()
            {
                User myUser = new User();
            }
            ...

        }

Note that the Object myUser have 3 properties: ID, Name, and Notes which is a list containing other properties : NoteID, NoteTitle, NoteDescription.

<Window.DataContext>
        <local:UserViewModel/>
    </Window.DataContext>
    <DataGrid Name="noteDataGrid" ItemsSource="{Binding DataContext}" AutoGenerateColumns="True">
        <DataGrid.Columns >
            <DataGridTextColumn Binding="{Binding Path=NoteID}" Header="ID"/>

            <DataGridTextColumn Binding="{Binding Path=Title}" Header="Title"/>

            <DataGridTextColumn Binding="{Binding Path=Description}" Header="Desc"/>
        </DataGrid.Columns>
    </DataGrid>

That's it, I know that there is something that does not match, but this is my first WPF (MVVM) Application, that's why i'll be so glad to have a solution.

Best Regards

Upvotes: 0

Views: 193

Answers (1)

amnezjak
amnezjak

Reputation: 2031

  1. In your VM you have to expose some collection, say, List<User> Users. Important: it must be a property.
  2. Then just add items to this collection in your constructor.
  3. Bind to the collection to DataGrid this way: ItemsSource="{Binding Users}".
  4. Voila.

Also, AutoGenerateColumns="True" will duplicate your columns (you add them both manually and automatically).

Upvotes: 1

Related Questions