WPF Datagrid ComboBox DataBinding [英] WPF Datagrid ComboBox DataBinding

查看:160
本文介绍了WPF Datagrid ComboBox DataBinding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我为什么这样工作;

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>

但这不是;

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

推荐答案

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

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

在第一个例子中,因为你的 ComboBox 是视觉树, RelativeSource 可以做它应该做的事情:走上UI树,寻找你要求的项目。但是在第二个例子中, DataGridComboBoxColumn 是一个 DependencyObject ,但它不是一个实际的UI元素 - 它是一个描述有关UI元素的信息。

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.

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

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

DataContext 将从窗口向下流到网格,所以除非你在UI中的这个时候再用别的东西来覆盖它,否则它仍然可以使用。

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.

或者如果不行,您可能需要将相关的集合添加到资源字典中,以便您可以在绑定中使用 Source = {StaticResource Suppliers} 获取它。

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.

这篇关于WPF Datagrid ComboBox DataBinding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆