WPF中DataGrid的ComboBox的简单绑定方式(绝对简单)

在写次文前先不得不说下网上的其他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(thisnew 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;
 
另附
先在资源中添加静态的实体,然后再Binding的时候引用资源,两步就搞定了:

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" />

 

转载于:https://www.cnblogs.com/sjqq/p/6758130.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值