WPF dataGrid下的ComboBox的綁定
Wpf中dataGrid中的某列是comboBox解決這個問題費了不少時間,不廢話了直接上代碼
xaml 代碼
<DataGridTemplateColumn Header="組名"> <DataGridTemplateColumn.CellTempLate> <DataTemplate> <ComboBox SelectedValue="{Binding Path=Name}" ItemSource={Binding Path=SelectionList,RelativeSource={RelativeSource AncestorType={x:Type UserControl},Mode=FindAncestor}}></ComboBox> <DataTemplate> <DataGridTemplateColumn.CellTempLate> </DataGridTemplateColumn >
xmal的代碼寫完了。下面寫后台代碼。
.cs代碼如下:
public ObservableCollection<string> SelectionList //ObservableCollection這是一個類,需引用(using System.Collections.ObjectModel) { get{return _selectionList;} set{_selectionList=value;} }
private observableCollection<string> _selectionList=new observableCollection<string>(); //這個是實現的重要一步
為什么用ObservableCollection類,可自行網上搜索
接下來應該給SelectionList 添加下來值了。
SelectionList .Add("Name1");
SelectionList .Add("Name2");
這樣ComboBox的下來框就有Name1和Name2了,當然SelectionList也可以添加后台查詢出來的DataTabel的值,無非就是加個循環而已
這是值給ComboBox添加值而已,最后一步,把從數據庫查出來的值綁定到ComboBox上,讓其實默認展示項
(select name ,field ...from table )查詢出一個DataTable的集合
dataGrid的name(自己起的名字)dataGrid.ItemSource=DataTable.DefaultView;
這樣查詢出的name將會綁定在ComboBox上。