绑定ComboBox控件到一个单独的源在DataGrid中 [英] Binding a Combobox control to a separate source within a DataGrid
问题描述
林试图DataGrid中,这将允许用户选择一个不同的表来的值内使用ComboBox。即时通讯使用一个ViewModel类DataContext的,这包含了对终端的TerminalTypes和的ObservableCollection另一个。
Im attempting to use a ComboBox within a DataGrid which will allow the user to select a value coming from a different table. Im using a ViewModel class as the DataContext and this contains an ObservableCollection for Terminals and another for TerminalTypes.
对电网的结合是好的,所有的行填充和DataGridTextColumns都显示正确的数据,但我的组合框是空的。
The binding on the grid is fine, all the rows are populated and the DataGridTextColumns all show the correct data, my ComboBox however is empty.
我知道的ObservableCollection林试图绑定到已被填充,如果我移动组合框的DataGrid外面按预期工作。
I know that the ObservableCollection Im attempting to bind to has been populated and if I move the ComboBox outside of the DataGrid it works as expected.
<my:DataGrid Name="MenuDetailGrid" AutoGenerateColumns="False" ItemsSource="{Binding Terminals}">
<my:DataGrid.Columns>
<my:DataGridTextColumn Header="Terminal Type ID" Binding="{Binding TERMINAL_TYPE_ID}" IsReadOnly="True" />
<my:DataGridTemplateColumn Header="Terminal Type">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox DisplayMemberPath="TTYPE_NAME" SelectedValuePath="TERMINAL_TYPE"
SelectedValue="{Binding TERMINAL_TYPE_ID}"
ItemsSource="{Binding TerminalTypes}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
显然约束力的行为是在不同的组合框时DataGrid的一部分,但是我有点难倒,为什么?
Obviously the binding behaviour is different on the ComboBox when part of the DataGrid but Im a bit stumped as to why?
有人可以帮我明白我做错了吗?
Can someone please help me understand what I am doing wrong?
推荐答案
的结合行为是一样的。然而就是在DataContext由ItemsControl中设置为当前项目一个DataTemplate,这是你的情况端子
-collection的成员。因此,TerminalTypes收集无法找到(除非你实现它也是在您的项目)。
The binding behaviour is the same. However is the DataContext in a DataTemplate set by the ItemsControl to current item and this is in your case a member of the Terminals
-collection. Therefore, the TerminalTypes-collection could not be found (unless you implement it also on your item).
你可以做的是在你的绑定使用相对源。有了这个,你可以导航到DataGrid的DataContext的,然后访问 TerminalTypes
-Collection:
What you can do is to use a relative source in your Binding. With this, you can navigate to the DataGrid's DataContext and then access your TerminalTypes
-Collection:
<ComboBox DisplayMemberPath="TTYPE_NAME"
SelectedValuePath="TERMINAL_TYPE"
SelectedValue="{Binding TERMINAL_TYPE_ID}"
ItemsSource="{Binding DataContext.TerminalTypes,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}" />
希望这有助于。做一个评论,如果没有。
Hope this helped. Make a comment if not.
这篇关于绑定ComboBox控件到一个单独的源在DataGrid中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!