数据模板和 "main" 网格中的用户控件之间的区别

Difference between usercontrol in datatemplate and in "main" grid

我创建了用户控件,其数据上下文是从另一个用户控件设置的。当我在主网格中插入此用户控件时,它工作正常。

<Grid>
    <local:ShowListView DataContext="{Binding ShowListViewModel}"/>
</Grid>

但是当我通过 DataTemplate 插入它时,像这样

<UserControl.Resources>
    <DataTemplate DataType="{x:Type showViewModels:ShowListViewModel}">
        <local:ShowListView />
    </DataTemplate>
</UserControl.Resources>
<Grid>
    <ContentControl Content="{Binding CurrentView}"/>
</Grid>

它抛出这个错误

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 控件包含这个

<ListBox ItemsSource="{Binding Shows}" BorderBrush="Transparent"
         HorizontalContentAlignment="Stretch">

和相关的视图模型

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);
    }
}

为什么第一种方法没有问题,但第二种方法会抛出错误?我应该更改什么以使其与 Datatemplate 一起使用?

删除 DataTemplate 中 UserControl 的 DataContext 属性:

<DataTemplate DataType="{x:Type showViewModels:ShowListViewModel}">
    <local:ShowListView />
</DataTemplate>

ShowListView 将在应用模板时自动获取 ShowListViewModel 对象作为其 DataContext,前提是您没有在某处显式设置其 DataContext 属性。

您还应确保在使用结果填充 ObservableCollection 之前执行查询。您可以通过调用 ToList() 方法来完成此操作:

public ShowListViewModel()
{         
    using (var db = new MSDBContext())
    {
        var shows = (from s in db.Shows select s).ToList();

        Shows = new ObservableCollection<Show>(shows);
    }
}