Wpf 如何在I';从DbSet绑定到某个实体?
我第一次尝试使用EntityFramework和WPF数据绑定 我有一些列表框。我已经将Wpf 如何在I';从DbSet绑定到某个实体?,wpf,binding,entity-framework-6,Wpf,Binding,Entity Framework 6,我第一次尝试使用EntityFramework和WPF数据绑定 我有一些列表框。我已经将ItemsSource设置为SomeDbContext.SomeEntity.ToList()以编程方式,我已按如下方式设置绑定: <ListBox Name="listbox" Margin="4" SelectedValuePath="Address" > <ListBox.ItemTemplate> <DataTemplate>
ItemsSource
设置为SomeDbContext.SomeEntity.ToList()代码>以编程方式,我已按如下方式设置绑定:
<ListBox Name="listbox" Margin="4" SelectedValuePath="Address" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Id}"></Label>
<Label Content="{Binding Address}"></Label>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Click="ButtonTest_Click">Open</Button>
这是我的实体:
public class Adresses
{
public int Id { get; set; }
public string Address { get; set; }
}
我的数据库上下文:
public class DatabaseContext : DbContext
{
public DbSet<Adresses> Addresses { get; set; }
}
公共类数据库上下文:DbContext
{
公共数据库集地址{get;set;}
}
我做错了什么
我想我的方法是错误的,因为我在将ItemsSource
设置为\u dbContext.Addresses.ToList()时创建了新对象
,但我不知道如何直接绑定到我的数据库集(或者是否可能)。我会将地址作为viewmodel属性进行管理ObservableCollection Addresses
。将其绑定到列表框的ItemsSource(在XAML中,而不是codebehind中),地址的更改将反映在UI中。当用户想要保存到DB时,从observablecollection中更新\u dbContext.Addresses
,然后保存。您所做的错误是ToList()
制作了一个副本,顺便说一句,它是一个在更改时不会引发任何事件的副本,因此即使您确实进行了更新,列表框无法知道它应该更新。最简单的方法是lb.ItemsSource=\u dbContext.Addresses.ToList()在按钮测试\u点击
的末尾,再次执行code>,但这并不是真正问题的真正解决方案。顺便说一句,Address
应该实现INotifyPropertyChanged
我将把地址作为viewmodel属性可观察到的收集地址进行管理。将其绑定到列表框的ItemsSource(在XAML中,而不是codebehind中),地址的更改将反映在UI中。当用户想要保存到DB时,从observablecollection中更新\u dbContext.Addresses
,然后保存。您所做的错误是ToList()
制作了一个副本,顺便说一句,它是一个在更改时不会引发任何事件的副本,因此即使您确实进行了更新,列表框无法知道它应该更新。最简单的方法是lb.ItemsSource=\u dbContext.Addresses.ToList()在按钮测试\u点击
的末尾,再次执行code>,但这并不是真正问题的真正解决方案。顺便说一句,地址
应该实现INotifyPropertyChanged
public class DatabaseContext : DbContext
{
public DbSet<Adresses> Addresses { get; set; }
}