c# - WPF DataGrid - 基于行动态绑定(bind) DataGridComboBoxColumn

标签 c# wpf data-binding datagrid datagridcomboboxcolumn

我有一个 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/

相关文章:

java - 将 Spinner<Integer> 绑定(bind)到现有 IntegerProperty

c# - 为什么我必须在 ASP 5 中的 app.UseMvc 之前调用 app.UseErrorHandler 才能正常工作?

c#:当我像这样初始化一个 boolean 数组时到底发生了什么

c# - MVVM 模式 - 可以将 UI 相关数据放入模型中吗?

c# - 使用服务依赖注入(inject)实例化 MyViewModel 时出现 NullReferenceException

c# - WPF ListView SelectedItems 数据绑定(bind) MVVM

C# Xamarin - 使用 SetValueForKey 将数据绑定(bind)到 UICollectionViewCell

c# - 在 VS 开发服务器和 IIS 上为 ASP.NET MVC 应用程序设置文化

c# - WCF Web 服务与 MySQL,读取 SQL 数据时出错?

c# - 如何将网格绑定(bind)到 WPF 中选定的 TreeView 项