WPF 数据网格组合框数据绑定 [英] WPF Datagrid ComboBox DataBinding

查看:22
本文介绍了WPF 数据网格组合框数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 supply} 获取它.

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 数据网格组合框数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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