我想創建可編輯的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。 –