I created user control, whose datacontext is set from another user control. When I insert this usercontrol in main grid, it works fine.
<Grid>
<local:ShowListView DataContext="{Binding ShowListViewModel}"/>
</Grid>
But when I insert it via DataTemplate, like this
<UserControl.Resources>
<DataTemplate DataType="{x:Type showViewModels:ShowListViewModel}">
<local:ShowListView />
</DataTemplate>
</UserControl.Resources>
<Grid>
<ContentControl Content="{Binding CurrentView}"/>
</Grid>
It throws this error
Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery, DbRawSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data.
ShowListView control contains this
<ListBox ItemsSource="{Binding Shows}" BorderBrush="Transparent"
HorizontalContentAlignment="Stretch">
and the relevant viewmodel
public ObservableCollection<ShowModel> Shows { get; set; }
public ShowListViewModel()
{
using (var db = new MSDBContext())
{
var shows = (from s in db.Shows select s).ToList();
Shows = new ObservableCollection<ShowModel>(shows);
}
}
Why the first method works without problem, but second one throws error? What should I change that it works with Datatemplate?
Remove the DataContext attribute of the UserControl in the DataTemplate:
<DataTemplate DataType="{x:Type showViewModels:ShowListViewModel}">
<local:ShowListView />
</DataTemplate>
The ShowListView will automatically get the ShowListViewModel object as its DataContext when the template is applied providing that you don't explicitly set its DataContext property somewhere.
You should also make sure to execute the query before populating the ObservableCollection
with the results. You can do this by calling the ToList()
method:
public ShowListViewModel()
{
using (var db = new MSDBContext())
{
var shows = (from s in db.Shows select s).ToList();
Shows = new ObservableCollection<Show>(shows);
}
}