datagrid根据datagrid列上数据不同加载不同的combobox下拉框并初始化下拉款值
时间: 2024-01-19 13:03:46 浏览: 206
可以通过DataGrid的CellEditEnding事件来实现根据不同的列数据加载不同的ComboBox下拉框,并初始化下拉框的值。具体实现步骤如下:
1. 在XAML中定义DataGrid列,并设置ComboBox作为该列的编辑模板:
```xml
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Header="序号" Binding="{Binding Id}" />
<DataGridTextColumn Header="名称" Binding="{Binding Name}" />
<DataGridTemplateColumn Header="类别">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Category}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.CategoryList, RelativeSource={RelativeSource AncestorType=DataGrid}}"
SelectedValue="{Binding Category, Mode=TwoWay}"
SelectedValuePath="Id"
DisplayMemberPath="Name" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
```
2. 在ViewModel中定义CategoryList属性,该属性用于存储所有的ComboBox下拉框的选项列表,并在构造函数中初始化该列表:
```c#
private ObservableCollection<Category> _categoryList;
public ObservableCollection<Category> CategoryList
{
get { return _categoryList; }
set { _categoryList = value; OnPropertyChanged(); }
}
public ViewModel()
{
// 初始化CategoryList列表
CategoryList = new ObservableCollection<Category>
{
new Category { Id = 1, Name = "类别1", Options = new ObservableCollection<string> { "选项1", "选项2", "选项3" } },
new Category { Id = 2, Name = "类别2", Options = new ObservableCollection<string> { "选项4", "选项5", "选项6" } }
};
}
```
3. 在DataGrid的CellEditEnding事件中,根据列数据的不同来动态加载相应的ComboBox选项,并初始化选中值:
```c#
private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.EditingElement is ComboBox comboBox && e.Column is DataGridTemplateColumn column)
{
// 获取当前行的数据对象
var item = (MyDataObject)e.Row.Item;
// 根据列名获取列数据
switch (column.Header)
{
case "类别":
// 根据类别获取选项列表
var category = CategoryList.FirstOrDefault(x => x.Name == item.Category);
if (category != null)
{
comboBox.ItemsSource = category.Options;
comboBox.SelectedValue = item.Option;
}
break;
}
}
}
```
上述代码中,根据列名获取列数据,然后根据该数据动态加载相应的ComboBox选项,并初始化选中值。其中,CategoryList列表中存储了所有的ComboBox选项列表。
阅读全文
相关推荐


















