我想使用 combobox 列创建一个双向可编辑的数据网格。 此数据网格连接到.NET实体框架。我怎么能这样做?你可以扩展我的代码吗?
SQL:
CREATE TABLE Languages(
L_Id INTEGER PRIMARY KEY IDENTITY(1,1),
L_Name VARCHAR(16) NOT NULL
);
CREATE TABLE Movies (
M_Id INTEGER PRIMARY KEY IDENTITY(1,1),
M_Title VARCHAR(128) NOT NULL,
M_Language_Id INTEGER NOT NULL,
CONSTRAINT MoviesToLanguages
FOREIGN KEY (M_Language_Id)
REFERENCES Languages (L_Id)
);
INSERT INTO Languages VALUES('subtitled');
INSERT INTO Languages VALUES('synchronized');
MainWindow.xaml
...
<DataGrid Name="MoviesDataGrid" Grid.Row="1" AutoGenerateColumns="False" ItemsSource="{Binding Movies}">
<DataGrid.Columns>
<DataGridTextColumn Header="Title" Binding="{Binding M_Title}" />
<DataGridTemplateColumn Header="Language" CanUserReorder="False">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock TextAlignment="Center" Text="{Binding Path=Languages.L_Name}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
???
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
...
CinemaViewModel.cs
private CinemaEntities _Entities;
public ObservableCollection<Movies> Movies{ get; private set; }
public CinemaViewModel()
{
_Entities = new CinemaEntities();
Movies = new ObservableCollection<Movies>(_Entities.Movies.Include("Languages"));
OnPropertyChanged("Movies");
}
private void Save()
{
_Entities.SaveChanges();
}
答案 0 :(得分:1)
在您的DataTemplate中:
<ComboBox ItemsSource="{Binding DataContext.Movies, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}" SelectedItem="{Binding WhateverPropertyReferencesTheMovieNavigationPropertyInYourEntities}" DisplayMemberPath="WhateverPropertyInTheMoviesYouWantToVisualizeInTheComboBox"/>