我想创建可编辑的DataGrid其单元既可以只读或可编辑(通过双击)... 我想所有editted细胞的保存到数据库,(通过实体框架)...如何编辑和保存WPF GridView到数据库?
然后在一些列中,我需要显示一个组合框而不是文本框。
我该如何去做到这一点?
我想创建可编辑的DataGrid其单元既可以只读或可编辑(通过双击)... 我想所有editted细胞的保存到数据库,(通过实体框架)...如何编辑和保存WPF GridView到数据库?
然后在一些列中,我需要显示一个组合框而不是文本框。
我该如何去做到这一点?
取决于您是否使用MVVM。
无论采用哪种方式,您都需要确定要如何保存。有没有保存按钮?或者编辑会在制作完成后立即保存。 (最后一个对你的数据库非常糟糕,但对你而言)
编辑产生一个你可以捕获的事件。同样点击保存按钮会产生一个事件。
保存按钮 因此,让我们假设你想要一个保存按钮。
那么当按钮点击事件发生时,你会调用代码保存到你的数据库。不知道你的分贝,我不能告诉你更多,除非这应该是一个不同的线程,所以它不会发生在UI线程上。查看Task.Run了解更多信息。
SAVE ON EDIT 基本上和上面一样,但是你最终会更频繁地和你的db交谈。每个按键真的,这就是为什么你的分贝更难。 基本上你捕获的按键或keyup事件,然后将信息保存到您的数据库。
使用此代码:
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; }
}
这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。 –