如何编辑WPF GridView并将其保存到数据库?
我想创建可编辑的DataGrid,其单元格可以是只读的,也可以是可编辑的(通过双击)。。。 我想将所有编辑的单元格保存到数据库(通过实体框架) 然后在一些列中,我需要显示一个组合框而不是文本字段如何编辑WPF GridView并将其保存到数据库?,wpf,entity-framework,wpf-controls,wpfdatagrid,Wpf,Entity Framework,Wpf Controls,Wpfdatagrid,我想创建可编辑的DataGrid,其单元格可以是只读的,也可以是可编辑的(通过双击)。。。 我想将所有编辑的单元格保存到数据库(通过实体框架) 然后在一些列中,我需要显示一个组合框而不是文本字段 如何实现这一点?取决于您是否使用MVVM 无论哪种方式,您都需要确定如何保存。有保存按钮吗?或编辑完成后立即保存。(最后一个对你的DB来说很糟糕,但取决于你) 编辑生成可以捕获的事件。同时单击“保存”按钮会生成一个事件 保存按钮 因此,假设您需要一个保存按钮 那么,当按钮单击事件发生时,您将调用代码以保
如何实现这一点?取决于您是否使用MVVM 无论哪种方式,您都需要确定如何保存。有保存按钮吗?或编辑完成后立即保存。(最后一个对你的DB来说很糟糕,但取决于你) 编辑生成可以捕获的事件。同时单击“保存”按钮会生成一个事件 保存按钮 因此,假设您需要一个保存按钮 那么,当按钮单击事件发生时,您将调用代码以保存到数据库中。在不了解数据库的情况下,我不能告诉您更多,除非这应该被分配到不同的线程,这样就不会在UI线程上发生。查看任务。运行以获取更多信息 编辑时保存 基本上与上面相同,但最终你会更频繁地与db交谈。每按一次键,这就是为什么你的数据库更难的原因。 基本上,您可以捕获按键或按键事件,然后将信息保存到数据库中 使用以下代码:
public class Window2Viewmodel : INotifyPropertyChanged
{
public Window2Viewmodel()
{
MyDbContext myDbContext = new MyDbContext();
Customers = new ObservableCollection<Customer>(myDbContext.Customers.Include("Cars").ToList());
SaveCommand = new RelayCommand(() =>
{
myDbContext.SaveChanges();
});
}
private ObservableCollection<Customer> _customers;
public ObservableCollection<Customer> Customers
{
get { return _customers; }
set
{
if (_customers != value)
{
_customers = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void OnPropertyChanged([CallermemberNmae]string propertyName = null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public RelayCommand SaveCommand { get; set; }
}
公共类Window2Viewmodel:INotifyPropertyChanged
{
公共Window2Viewmodel()
{
MyDbContext MyDbContext=新的MyDbContext();
Customers=newobservetecollection(myDbContext.Customers.Include(“Cars”).ToList());
SaveCommand=newrelayCommand(()=>
{
myDbContext.SaveChanges();
});
}
私人可观测收集客户;
公开收集客户
{
获取{return\u customers;}
设置
{
如果(_客户!=价值)
{
_顾客=价值;
OnPropertyChanged();
}
}
}
公共事件PropertyChangedEventHandler PropertyChanged=委托{};
public void OnPropertyChanged([CallermemberNmae]字符串propertyName=null)
{
PropertyChanged(这是新的PropertyChangedEventArgs(propertyName));
}
public RelayCommand SaveCommand{get;set;}
}
这个XAML代码:
<Window.Resources>
<local:Window2Viewmodel x:Key="VM"/>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource VM}}">
<DataGrid Name="testDataGrid" ItemsSource="{Binding Customers}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding FName}" Header="Name"/>
<DataGridTextColumn Binding="{Binding LName}" Header="Lastname"/>
</DataGrid.Columns>
</DataGrid>
<Button Content="Save" VerticalAlignment="Bottom" Command="{Binding SaveCommand}"/>
</Grid>
非常感谢您的帮助。我不使用MVVM,我的数据库是SQL Server。谢谢你的帮助,你能给我完整的示例代码吗?