WPF ListView databinding to ObservableCollection

2019-08-28 23:24发布

问题:

In WPF app I have a ListView:

<ListView Height="100" Width="434" x:Name="lvItems" ItemsSource="{Binding ElementName=MainWindow, Path=ShowQuCollection}" >
 <ListView.View>
  <GridView>
   <GridViewColumn Header="Date" Width="100" DisplayMemberBinding="{Binding Date}"/>
   <GridViewColumn Header="Time" Width="100" DisplayMemberBinding="{Binding Time}"/>
   <GridViewColumn Header="Description" Width="200" DisplayMemberBinding="{Binding Description}"/>
  </GridView>
 </ListView.View>

which is connected with ObservableCollection through databinding:

ObservableCollection<ShowsQu> _ShowQuCollection =
    new ObservableCollection<ShowsQu>();

public ObservableCollection<ShowsQu> ShowQuCollection
{ get { return _ShowQuCollection; } }

public class ShowsQu
{
public string ShowCode { get; set; }
public DateTime Date { get; set; }
public TimeSpan Time { get; set; }
public string Description { get; set; }
}

This ObservableCollection is placed in the code-behind file of the same window, where ListView is MainWindow. Everything works fine.

Now I add yet another ListView to different window and in this case databinding isn't working. This databinding piece of XAML I didn't change:

ItemsSource="{Binding ElementName=MainWindow, Path=ShowQuCollection}

How should I change this ListView databinding declaration (ListView in SecondWindow) in order it was connected with the ObservableCollection in the MainWindow?

回答1:

ElementName bindings only look in the current window. You would need to set the Binding Source or (more likely) local DataContext explicitly to that other window.

However, a better approach would be to remove ShowQuCollection from the Window class and make it part of a separate "view model" class (non-visual, data only). Then you could make both Windows have the same DataContext (an instance of the view model class) and you would not need to use an ElementName binding at all. ElementName bindings are typically used when something depends on another control in the UI (e.g. binding a Panel's Visibility to a CheckBox's IsChecked), rather than as a way to refer to actual data.



回答2:

If by 'different window' you mean a different class, then you need to set the DataContext of the second window to be the same as the datacontext of the first.