开发者

WPF DataGrid Binding on Columns

开发者 https://www.devze.com 2023-03-21 14:47 出处:网络
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

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.


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


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>


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

0

精彩评论

暂无评论...
验证码 换一张
取 消