首页 > 解决方案 > WPF 将 DataGridComboBoxColumn 绑定到 ComboBox 的 SelectedItem

问题描述

我正在WPF(MVVM)中构建一个应用程序。用户要在 a 中进行选择ComboBox,并且该选择应该过滤 a 中DataGridComboBoxColumn(DGCBC) 中可用的结果DataGrid

但是我不知道如何将其绑定ComboBox SelectedItem到 DGCBC。我确实设法ComboBox过滤了第二个结果ComboBox,但是该逻辑似乎无法很好地转移到 DGCBC。

我试过的:

我的ComboBox

<ComboBox
    DisplayMemberPath="PropertyName1"
    ItemsSource="{Binding Collection1}"
    Loaded="{s:Action NameOfMethodToPopulateComboBox}"
    SelectedItem="{Binding PropertyHolder, UpdateSourceTrigger=PropertyChanged}"/>

PropertyHolder在 中选择项目时运行ComboBox,如果它不为空,则运行添加到ObservableCollection绑定到 DGCBC 的方法。它看起来像这样:

private ClassName _currentSelectedItem;
public ClassName CurrentSelectedItem {
    get { return this,._selectedItem; }
    set { SetAndNotify(ref this._selectedItem, value);
        if (value != null) {
           FillDataGridComboBoxColumn();
        }
    }
}

该方法FillDataGridComboBoxColumn()看起来像这样(缩写):

DataSet ds = new();
    // Code to run stored procedure
    // CurrentSelectedItem is given as parameter value

DataTable dt = new();
dt = ds.Tables[0];

MyObservableCollection.Clear();

for (int i = 0; i < dt.Rows.Count; i++) {

    DataRow dr = dt.NewRow();
    dr = dt.Rows[i];
    HolderClass holderClass = new(); // this is the class that is bound to the observablecollection
    holderClass.PropertyName = dr["PropertyName2"].ToString();
    MyObservableCollection.Add(holderClass);

这是 和 的DataGridXAML DataGridComboBoxColumn

<DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding MyObservableCollection}">

        <DataGridComboBoxColumn
            SelectedValueBinding="{Binding PropertyName2, UpdateSourceTrigger=PropertyChanged}"
            SelectedValuePath="PropertyName2"
            DisplayMemberPath="PropertyName2"
            ItemsSource="{Binding MyObservableCollection}">
/>

</DataGrid>

当我调试时,DataGridComboBoxColumn能够获得正确的行数 - 但它们只是空占位符;空白。如果我在代码中设置断点,我会看到集合确实加载了正确的值,但它们只是没有显示。

我猜我对 DGCBC 的绑定做错了。

谢谢你。

标签: c#wpfmvvmcomboboxdatagrid

解决方案


DataGridComboBoxColumn ItemSource必须设置Static Resource为:

<Window.Resources>
    <CollectionViewSource x:Key="MyObservableCollection" Source="{Binding MyObservableCollection}"/>
</Window.Resources>

然后,在 XAML 中DataGridComboBoxColumn

<DataGridComboBoxColumn
    ItemsSource="{Binding Source={StaticResource MyObservableCollection}}"
    DisplayMemberPath="Property2">
</DataGridComboBoxColumn>

推荐阅读