我正在处理一系列问题。
- 我有一个动态数据集,我手动将其组装成DataTable。
- 我必须自动生成列,因为数据不是静态的。
- 我需要将组合框的ItemsSource绑定到每个单元格中定义的Observable集合。
尽管我认为这很容易,但ComboBox无法看到DataView中的DataItem,而是尝试直接绑定到DataView。
我在这里提供了一个示例项目:
https://github.com/5flags/DataGridBindingIssue
现在,这显然是为了演示问题而刻意制造的。我无法在此时更改数据结构,因此任何解决方案都必须在XAML中完成。
要查看问题,请使用Snoop(或等效工具)查看ComboBoxes上的绑定错误。
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 Error: 40 : BindingExpression路径错误:'Options'属性在'object''DataRowView'(HashCode=22264221)'上未找到。BindingExpression:Path=Options; DataItem='DataRowView' (HashCode=22264221); 目标元素为'ComboBox' (Name=''); 目标属性为'ItemsSource' (type 'IEnumerable')
System.Windows.Data Error: 40 : BindingExpression路径错误:'SelectedOption'属性在'object''DataRowView'(HashCode=22264221)'上未找到。BindingExpression:Path=SelectedOption; DataItem='DataRowView' (HashCode=22264221); 目标元素为'ComboBox' (Name=''); 目标属性为'SelectedValue' (type 'Object')
Binding.Path
值前面加上'DataContext.'
:{Binding Path=DataContext.SelectedOption, ...}
。这样就可以从DataRowView
移动到你的数据项了。 - Sheridan