【问题标题】:WPF - Bind DataGrid ComboBoxColum to DataSet Table Filed with Values from another tableWPF - 使用来自另一个表的值将 DataGridComboBoxColumn 绑定到 DataSet 表字段
【发布时间】:2014-11-28 15:52:57
【问题描述】:

我正在尝试将我的 C# 代码转换为 xaml。

有效的c#代码是

        g_DataGrid[TablesManagerDataGrids.DG_Idx.DG_Fixtures].SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = g_dataSet.Tables[TABLE_FIXTURES] })

        DataGridComboBoxColumn colPlatform = new DataGridComboBoxColumn();
        colPlatform.Header = COL_FIXTURE_PLATFORM;
        colPlatform.ItemsSource = g_dataSet.Tables[TABLE_PLATFORM].Rows;
        colPlatform.DisplayMemberPath = "[" + COL_PLATFORM_NAME + "]";
        colPlatform.SelectedValuePath = "[" + COL_PLATFORM_IDX + "]";
        Binding temp = new Binding(COL_FIXTURE_PLATFORM);
        colPlatform.SelectedValueBinding = new Binding(COL_FIXTURE_PLATFORM);
        colPlatform.Width = new DataGridLength(1, DataGridLengthUnitType.Star); 

该代码将 ComboBox 列添加到数据网格以修改表 TABLE_FIXTURES 中的列 COL_FIXTURE_PLATFORM。 ComboBox 的值来自COL_PLATFORM_IDX 列中的表TABLE_PLATFORM。 ComboBox DropDownList 的字符串来自COL_PLATFORM_NAME 列中的表TABLE_PLATFORM。

现在我正在尝试将此代码转换为 xaml 代码,但我对这种语言太陌生了。 以下代码是我经过一些测试后能写出的最好的代码,但它不是我之前描述的。

DataContext 设置为我的 DataSet.Tables

            this.DataContext = g_Dataset.CurrentDataSet.Tables;

XAML 代码是:

    <DataGrid x:Key="DG_Fixtures_Structure" AutoGenerateColumns="false" ItemsSource="{Binding Path=[Fixtures]}" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" 
                            Binding="{Binding Path=Name}"/>
        <DataGridComboBoxColumn Header="Platform" 
                                ItemsSource="{Binding RelativeSource={RelativeSource Findancestor, AncestorType={x:Type Window}}, Path=DataContext[Platform]}"
                                DisplayMemberPath="Name"
                                SelectedValuePath="Index"
                                SelectedValueBinding="{Binding Path=Platforms}"/>
    </DataGrid.Columns>
</DataGrid>

加载数据网格时,调试器显示以下错误,并且组合框中没有数据。

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Window', AncestorLevel='1''. BindingExpression:Path=PlacementTarget.DataContext[Platform]; DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=12880602); target property is 'ItemsSource' (type 'IEnumerable')

有人可以帮助我吗?

【问题讨论】:

    标签: wpf xaml datagrid combobox dataset


    【解决方案1】:

    最后,我找到了一种使它起作用的方法/解决方法。 解决方法是在创建类之后在代码中设置ItemsSource。

    似乎 WPF 无法解析分配,因为通过调试,DataGrids 中为组合框设置的 ItemSource 始终为空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      相关资源
      最近更新 更多