andineupert
andineupert

Reputation: 351

WPF DataGrid Binding on Columns

hope this wasn't asked already, but I can't find an answer. I got a ViewModel set as DataContext in my xaml. In this ViewModel is a List< Dealer>-property. Dealer has some Properties which should be displayed in a datagrid (as columns, but not all of them). I tried to implement it like this:

<Grid x:Name="myGrid" DataContext="{Binding Source={StaticResource createGameVM}}">
...
   <DataGrid Name="dealerList" AutoGenerateColumns="False" ItemsSource="DealerList">
      <DataGrid.Columns>
         <DataGridTextColumn Header="ID" Width="30"  Binding="{DealerId}" />                        
         <DataGridTextColumn Header="Name" Width="*" Binding="{DealerName}" />                       
      </DataGrid.Columns>
   </DataGrid>
...
</Grid>

In this case the PropertyChanged in the ViewModel is null, so nothing is updated when DealerList changes. (But items which are in DealerList, before setting DataContext are displayed correctly). Don't know how to solve this.

Upvotes: 2

Views: 10553

Answers (3)

Yuf
Yuf

Reputation: 610

Besides using ObservableCollection, you can also create your own derived list class and implement INotifyCollectionChanged.

Upvotes: 0

Tom Studee
Tom Studee

Reputation: 10452

Try this:

<Grid x:Name="myGrid" DataContext="{Binding Source={StaticResource createGameVM}}">
...
   <DataGrid Name="dealerList" AutoGenerateColumns="False" ItemsSource="{Binding DealerList}">
      <DataGrid.Columns>
         <DataGridTextColumn Header="ID" Width="30"  Binding="{DealerId}" />                        
         <DataGridTextColumn Header="Name" Width="*" Binding="{DealerName}" />                       
      </DataGrid.Columns>
   </DataGrid>
...
</Grid>

Upvotes: 1

RandomEngy
RandomEngy

Reputation: 15413

Bind to an ObservableCollection<Dealer> on your ViewModel instead. That way it will be automatically updated when the collection changes.

Upvotes: 7

Related Questions