且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF 数据网格组合框数据绑定

更新时间:2023-10-04 14:23:10

这是因为 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.