3

谁能告诉我为什么会这样?

<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}}}" />

第二个片段在编辑时未显示供应商名称列表...

4

2 回答 2

5

这是因为 aDataGridComboBoxColumn不是用户界面元素,而是ComboBox

在第一个示例中,因为您ComboBox是可视化树的一部分,所以RelativeSource可以做它应该做的事情:沿着 UI 树查找您要求的项目。但在第二个例子中,它DataGridComboBoxColumn是一个DependencyObject但它不是一个实际的 UI 元素——它是一个描述关于 UI 元素的东西的对象。

您可以尝试ElementName改用,并为您的根窗口命名。或者,您可能只需:

<DataGridComboBoxColumn ...
   ItemsSource="{Binding Path=Suppliers}" />

它将从DataContext窗口向下流向网格,因此除非您此时在 UI 中用其他内容覆盖它,否则它仍然可用。

或者,如果这不起作用,您可能希望将相关集合添加到资源字典中,以便您可以Source={StaticResource suppliers}在绑定中使用 a 获取它。

于 2010-11-07T23:33:36.347 回答
0

原因是找不到 DataGridComboBoxColumn 的 ItemsSource。

您将需要使用 RelativeSource 绑定并将其指向正确的 DataContext AncestorType。这将需要一些试验和错误才能找到包含您的列表以满足您的 ItemsSource 的 DataContext。

于 2011-12-16T21:46:25.923 回答