2010-11-07 90 views
3

谁能告诉我为什么这个工作;WPF Datagrid ComboBox DataBinding

<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列表...

回答

5

这是因为一个DataGridComboBoxColumn不是用户界面元素,但ComboBox是。

在第一个示例中,因为您的ComboBox是可视化树的一部分,因此RelativeSource可以执行应有的操作:沿UI树查找您要求的项目。但在第二个示例中,DataGridComboBoxColumnDependencyObject,但它不是一个实际的UI元素 - 它是描述有关UI元素的对象。

您可以尝试使用ElementName来代替,并为您的根窗口命名。或者,你也许可以用只是为了脱身:

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

DataContext会从窗口向下流动到电网,因此,除非您overidden它与别的东西在这一点上的UI,它我仍然可以使用。

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

+0

发现ElementName似乎没有工作出于同样的原因,并且Path = Suppliers不起作用,因为DataGrid的DataContext已经绑定到行集合。结束了DataTemplates,并使用MultiBinding&a Converter在非编辑模式下显示名称。无论如何,你回答*为什么*它不起作用是正确的:) – 2010-11-09 01:07:18

0

原因是无法找到DataGridComboBoxColumn的ItemsSource。

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

+0

问题中的第一个示例指示应该从哪里检索ItemsSource。你将如何通过DataGridComboBoxColumn.ItemsSource访问它? – 2012-01-12 03:26:30