Reputation: 43
I am trying to load data into a ListView in WPF using a Stored Procedure and Entity Framework. When I first load the User Control the ListView loads the data just fine. I then call the same code to refresh the data and I can see through debugging that the ListItems count changes but the data on the front end screen does not update.
XAML
<ListView Name="DocsListView" ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn Header="Documents" DisplayMemberBinding="{Binding Documents}"/>
</GridView>
</ListView.View>
</ListView>
Code Behind
public void LoadDocs()
{
Context _Context = new Context();
DocsListView.ItemsSource = null;
DocsListView.ItemsSource = _Context.SP_GetDocuments(1).ToList();
_Context = null;
}
Can someone please help me figure out what I'm doing wrong? I'm using VS2012, .Net 4.5, and EF 5.0.
Upvotes: 4
Views: 6379
Reputation: 3284
I´m not sure whats causing the Problem, generally I would recommend to use a DependencyProperty!
But you could try to refresh the ListView like that:
ICollectionView view = CollectionViewSource.GetDefaultView(DocsListView.ItemsSource);
view.Refresh();
If this is going to be a bigger Project I strongly recommend to have a look at the MVVM DesignPattern!
WPF and MVVM play well together. There are nice Libraries you can use like MVVMLight.
Also you should have a look at the INotifyPropertyChanged Interface.
XAML-Code (Don´t forget to set the DataContext)
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<ListView Name="DocsListView" ItemsSource="{Binding Data}">
<ListView.View>
<GridView>
<GridViewColumn Header="Documents" DisplayMemberBinding="{Binding Documents}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
C# Code-Behind (ObservableCollection refreshes the UI automatically if a Item gets added or deleted):
public ObservableCollection<YourEntity> Data
{
get { return (ObservableCollection<YourEntity>)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
// Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(ObservableCollection<YourEntity>), typeof(MainWindow), null);
public void LoadDocs()
{
Context _Context = new Context();
if(Data == null)
{
Data = new ObservableCollection<YourEntity>();
}
else
{
Data.Clear();
}
foreach(var doc in _Context.SP_GetDocuments(1).ToList())
{
Data.Add(doc);
}
_Context = null;
}
Upvotes: 3