在写次文前先不得不说下网上的其他wpf的DataGrid绑定ComboBox的方式,看了之后真是让人欲仙欲死。
首先告诉你一大堆的模型,一大堆的控件模板,其实或许你紧紧只想知道怎么让combobox怎么显示出来而已。
惯例先上图:
达到这样的效果其实很简单,除了让数据模型之外紧紧只有几行代码。
先看数据模型:
01.
public
class
VModel : INotifyPropertyChanged
02.
{
03.
private
string _Name;
04.
05.
public
string Name
06.
{
07.
get {
return
_Name; }
08.
set
09.
{
10.
if
(_Name != value)
11.
_Name = value;
12.
OnPropertyChanged(
"Name"
);
13.
}
14.
}
15.
16.
private
List<string> _Desciption;
17.
18.
public
List<string> Desciption
19.
{
20.
get {
return
_Desciption; }
21.
set {
22.
if
(_Desciption != value)
23.
_Desciption = value;
24.
OnPropertyChanged(
"Desciption"
);
25.
}
26.
}
27.
28.
public
event PropertyChangedEventHandler PropertyChanged;
29.
30.
protected
void
OnPropertyChanged(string propertyName)
31.
{
32.
if
(string.IsNullOrEmpty(propertyName))
throw
new
ArgumentNullException(
"propertyName"
);
33.
PropertyChangedEventHandler handler = PropertyChanged;
34.
if
(handler !=
null
) handler(
this
,
new
PropertyChangedEventArgs(propertyName));
35.
}
36.
37.
}
后面的OnPropertyChanged无需在意 是为了达到数据动态变化 ,一般是不需要的
看下datagrid 的combobox的模板 这是重点
01.
<DataGrid AutoGenerateColumns=
"False"
Height=
"236"
HorizontalAlignment=
"Left"
Margin=
"12,0,0,0"
Name=
"dataGrid1"
VerticalAlignment=
"Top"
Width=
"471"
>
02.
<DataGrid.Columns>
03.
<DataGridTextColumn Header=
"Header1"
Binding=
"{Binding Name}"
/>
04.
<DataGridTemplateColumn Header=
"Template"
>
05.
<DataGridTemplateColumn.CellTemplate>
06.
<DataTemplate>
07.
<ComboBox ItemsSource=
"{Binding Desciption}"
/>
08.
</DataTemplate>
09.
</DataGridTemplateColumn.CellTemplate>
10.
</DataGridTemplateColumn>
11.
</DataGrid.Columns>
12.
</DataGrid>
看到了 吗 总共两列 一个textbox 一个combobox 就是这么简单 除过数据模型之外紧紧几行代码就可以搞定!
数据的初始化:
01.
List<VModel> vs =
new
List<VModel>();
02.
VModel v1 =
new
VModel();
03.
v1.Name =
"Sean"
;
04.
v1.Desciption =
new
List<string>();
05.
v1.Desciption.Add(
"1"
);
06.
v1.Desciption.Add(
"2"
);
07.
v1.Desciption.Add(
"3"
);
08.
vs.Add(v1);
09.
dataGrid1.ItemsSource = vs;
public ObservableCollection<Department> listDepartments{set;get;}
listDepartments = DB.GetCollection<Department>();
this.DataContext = this;
<Window.Resources>
<CollectionViewSource x:Key="departments" Source="{Binding listDepartments}" />
</Window.Resources>
<DataGridComboBoxColumn Width="100" Header="专业组" SelectedValuePath="Name" TextBinding="{Binding Department}" ItemsSource="{Binding Source={StaticResource departments}}" DisplayMemberPath="Name" />