我有一个 ObservableCollection
对象。这些对象显示在 DataGrid
和 `SelectedObject
我有一个属性 PossibleParentObjects
,它返回一个基于 SelectedObject 的对象的 List
。
我想让这个属性填充驻留在 DataGrid
列中的 ComboBox
我该怎么做?
这是我目前所拥有的...显然不工作:
<DataGrid Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
AlternatingRowBackground="AntiqueWhite" AlternationCount="2"
ItemsSource="{Binding AllObjects, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedObject}"
CanUserAddRows="True" CanUserDeleteRows="True"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name, Mode=TwoWay}" Header="Name"/>
<DataGridTextColumn Binding="{Binding Abbr, Mode=TwoWay}" Header="Abbreviation"/>
<DataGridComboBoxColumn Header="Parent Object" Width="120"
SelectedItemBinding="{Binding Path=Id, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Name"
ItemsSource="{Binding Path=AllObjects,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}">
</DataGridComboBoxColumn>
<DataGridTextColumn Binding="{Binding Desc, Mode=TwoWay}" Header="Description"/>
</DataGrid.Columns>
<i:Interaction.Triggers>
<i:EventTrigger EventName="CurrentCellChanged">
<i:InvokeCommandAction Command="{Binding DataGridChanged}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>
最佳答案
参见 this Stackoverflow question其中讨论了类似的问题。
基本思路如下:
- 将数据网格列绑定(bind)到 View 模型中的单个属性,我们称它为“ParentObjects”
- 将数据网格的选定行绑定(bind)到 View 模型中的另一个属性。 在该属性的 setter 中,您应该检索 DataGridComboBox 列的组合框所需的数据项,并使用它来设置“ParentObjects”属性
这样,无论何时用户更改他想要查看的行,它都会自动检索正确的对象并填充组合框列。 换句话说,您不使用组合框的源来检索它,而是在所选行发生更改时进行检索。您必须这样做 - 属性系统不允许参数。
我知道这是我在这里给出的一般描述,而不是代码,但我认为您会明白要点。
关于c# - WPF DataGrid - 基于行动态绑定(bind) DataGridComboBoxColumn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31970769/