简体   繁体   中英

Bind data to the ListView control in WPF using MVVM

I have tried to bind the data into the ListView control:

<ListView Margin="8" Height="400" Width="650" 
    ItemsSource="{Binding Path=MyData}">
    <ListView.View>
         <GridView>
             <GridViewColumn Header="ID" Width="Auto" 
                  DisplayMemberBinding="Binding Path=ID}" >
             </GridViewColumn>
             <GridViewColumn DisplayMemberBinding="{Binding Path=Name}" 
                  Header="Name" Width="100"/>
             <GridViewColumn DisplayMemberBinding="{Binding Path=Price}" 
                  Header="Price" Width="100"/>
             <GridViewColumn DisplayMemberBinding="{Binding Path=Author}" 
                  Header="Author" Width="100"/>
             <GridViewColumn DisplayMemberBinding="{Binding Path=Catalog}" 
                  Header="Catalog" Width="100"/>
           </GridView>
    </ListView.View>
</ListView>

  ObservableCollection<TableInfo> _MyData
  public ObservableCollection<TableInfo> MyData{ get; set; }

However, it's not display anything in the window but MyData is an ObservableCollection . How do I bind the data?

Tanya,

If you set your view model properly and if you're sure that your MyData collection is not null or empty, try to remove the "Path" keywords from your xaml:

<ListView Margin="8" Height="400" Width="650" 
    ItemsSource="{Binding Path=MyData}">
    <ListView.View>
         <GridView>
             <GridViewColumn Header="ID" Width="Auto" 
                  DisplayMemberBinding="{Binding ID}" >
             </GridViewColumn>
             <GridViewColumn DisplayMemberBinding="{Binding Name}" 
                  Header="Name" Width="100"/>
             <GridViewColumn DisplayMemberBinding="{Binding Price}" 
                  Header="Price" Width="100"/>
             <GridViewColumn DisplayMemberBinding="{Binding Author}" 
                  Header="Author" Width="100"/>
             <GridViewColumn DisplayMemberBinding="{Binding Catalog}" 
                  Header="Catalog" Width="100"/>
           </GridView>
    </ListView.View>
</ListView>

If this doesn't help, check the debug output and post it, we will definitely figure something out.

Your XAML looks fine to me.

Make sure you are setting the DataContext correctly.

yourView.DataContext = YouViewModel;

When the Binding is first evaluated, it may (depending on your code) find null. It does not get notified if you later set it to something sensible.

Try to make sure that you create the ObservableCollection in your classes costructor and not overwrite it somewhere else. You could alternativly implement INotifyPropertyChanged and raise a PropertyChanged event on te MyData setter.

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