WPF Datagrid ComboBox DataBinding

。_饼干妹妹 提交于 2019-12-01 06:39:08

问题


Can anyone tell me why this works;

<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>

but this doesn't;

<DataGridComboBoxColumn Header="Combo" DisplayMemberPath="SupplierName" SelectedValuePath="SupplierID" 
  SelectedValueBinding="{Binding SupplierID}"
  ItemsSource="{Binding Path=DataContext.Suppliers, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

Second snippet does not show the list of SupplierName on edit...


回答1:


It's because a DataGridComboBoxColumn isn't a user interface element, but ComboBox is.

In the first example, because your ComboBox is part of the visual tree, RelativeSource can do what it's supposed to do: walk up the UI tree looking for the item you've asked for. But in the second example, the DataGridComboBoxColumn is a DependencyObject but it's not an actual UI element - it's an object that describes something about the UI element.

You could try using ElementName instead, and give a name to your root window. Or, you might be able to get away with just:

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

The DataContext will flow down from the window to the grid, so unless you've overidden it with something else at this point in the UI, it'll still be available.

Or if that doesn't work, you might want to add the relevant collection to a resource dictionary so you can get it with a Source={StaticResource suppliers} in the binding.




回答2:


The reason is that the ItemsSource for the DataGridComboBoxColumn can not be found.

You will need to use the RelativeSource Binding and point it to the correct DataContext AncestorType. This will take some trial and error to find the DataContext that contains your list to satisfy your ItemsSource.



来源:https://stackoverflow.com/questions/4120027/wpf-datagrid-combobox-databinding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!