【发布时间】:2023-03-19 03:56:01
【问题描述】:
我正在努力解决一系列问题。
- 我有一个动态数据集,我手动将其组装成一个 DataTable。
- 我必须自动生成列,因为数据不是静态的。
- 我需要将组合框的 ItemsSource 绑定到每个单元格中定义的 Observable 集合。
虽然我认为这很容易,但 ComboBox 在 DataView 中看不到 DataItem,而是尝试直接绑定到 DataView。
我在这里整理了一个示例项目:
https://github.com/5flags/DataGridBindingIssue
现在,显然是为了证明这个问题。此时我无法更改数据结构,因此任何解决方案都必须在 XAML 中完成。
要查看问题,请使用 Snoop(或等效项)查看 ComboBox 上的绑定错误。
DataGrid 的设置如下:
<DataGrid AutoGenerateColumns="True" AutoGeneratingColumn="DataGrid_OnAutoGeneratingColumn" CanUserAddRows="False" x:Name="TheDataGrid" ItemsSource="{Binding Data}">
<DataGrid.Resources>
<DataTemplate x:Key="dataItemCellTemplate">
<ComboBox SelectedValue="{Binding Path=SelectedOption, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding Options}"/>
</DataTemplate>
</DataGrid.Resources>
</DataGrid>
自动生成的事件处理程序是:
private void DataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(string))
{
var col = new DataGridTextColumn {Binding = new Binding(e.PropertyName), Header = e.PropertyName};
e.Column = col;
}
else if (e.PropertyType == typeof(DataItem))
{
var col = new DataGridTemplateColumn
{
CellTemplate = (DataTemplate) TheDataGrid.FindResource("dataItemCellTemplate"),
CellEditingTemplate = (DataTemplate)TheDataGrid.FindResource("dataItemCellTemplate"),
Header = e.PropertyName
};
e.Column = col;
}
}
组合上的绑定错误是:
System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“DataRowView”(HashCode=22264221)上找不到“选项”属性。绑定表达式:路径=选项; DataItem='DataRowView' (HashCode=22264221);目标元素是 'ComboBox' (Name='');目标属性是“ItemsSource”(类型“IEnumerable”)
System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“DataRowView”(HashCode=22264221)上找不到“SelectedOption”属性。 BindingExpression:Path=SelectedOption; DataItem='DataRowView' (HashCode=22264221);目标元素是 'ComboBox' (Name='');目标属性是“SelectedValue”(类型“对象”)
【问题讨论】:
-
能否请您显示您的数据绑定 XAML?
-
编辑了问题以包含更多信息。
-
您能否确认您的
DataTable中有一个名为Options的列和一个名为SelectedOption的列? -
单元格中的DataItem上面有SelectedOption和Options。
-
“数据项”是什么意思?我以为你说你正在使用
DataTable...你的意思是DataRow?是什么让您认为Binding正在到达DataView? Visual Studio 中的Output窗口出现什么错误?
标签: c# wpf wpfdatagrid