简体   繁体   中英

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

  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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM