谁能告诉我为什么这行得通;
<DataGridTemplateColumn Header="Supplier">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox DisplayMemberPath="SupplierName" SelectedValuePath="SupplierID"
SelectedValue="{Binding SupplierID}"
ItemsSource="{Binding Path=DataContext.Suppliers, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
但这不是;
<DataGridComboBoxColumn Header="Combo" DisplayMemberPath="SupplierName" SelectedValuePath="SupplierID"
SelectedValueBinding="{Binding SupplierID}"
ItemsSource="{Binding Path=DataContext.Suppliers, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
第二个片段不显示编辑时的 SupplierName 列表...
最佳答案
这是因为 DataGridComboBoxColumn
不是用户界面元素,但 ComboBox
是。
在第一个示例中,因为您的 ComboBox
是可视化树的一部分,所以 RelativeSource
可以做它应该做的事情:在 UI 树中向上走寻找项目你问过。但在第二个示例中,DataGridComboBoxColumn
是一个 DependencyObject
但它不是实际的 UI 元素 - 它是一个描述 UI 元素相关内容的对象。
您可以尝试使用 ElementName
,并为您的根窗口命名。或者,您也许可以逃脱惩罚:
<DataGridComboBoxColumn ...
ItemsSource="{Binding Path=Suppliers}" />
DataContext
将从窗口向下流动到网格,因此除非您此时在 UI 中用其他东西覆盖它,否则它仍然可用。
或者,如果这不起作用,您可能希望将相关集合添加到资源字典中,以便您可以通过绑定(bind)中的 Source={StaticResource suppliers}
获取它。
关于WPF 数据网格组合框数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4120027/