Sta*_*ams 3 data-binding wpf datagrid datagridcomboboxcolumn
谁能告诉我为什么这样有效;
<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>
Run Code Online (Sandbox Code Playgroud)
但这不;
<DataGridComboBoxColumn Header="Combo" DisplayMemberPath="SupplierName" SelectedValuePath="SupplierID"
SelectedValueBinding="{Binding SupplierID}"
ItemsSource="{Binding Path=DataContext.Suppliers, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
Run Code Online (Sandbox Code Playgroud)
第二个片段在编辑时不显示SupplierName列表...
这是因为a DataGridComboBoxColumn不是用户界面元素,而是ComboBox.
在第一个示例中,因为您ComboBox是可视化树的一部分,所以RelativeSource可以执行它应该执行的操作:沿着UI树查找您要求的项目.但是在第二个例子中,它DataGridComboBoxColumn是一个DependencyObject但它不是一个真正的UI元素 - 它是一个描述UI元素的对象.
您可以尝试使用ElementName,并为您的根窗口命名.或者,你可能只能逃脱:
<DataGridComboBoxColumn ...
ItemsSource="{Binding Path=Suppliers}" />
Run Code Online (Sandbox Code Playgroud)
该DataContext会从窗口向下流动到电网,因此,除非您overidden它在UI这一点别的东西,它仍然是可用的.
或者,如果这不起作用,您可能希望将相关集合添加到资源字典中,以便您可以使用Source={StaticResource suppliers}绑定中的a来获取它.