I am building an app in WPF
(MVVM).
The user is to make a selection in a ComboBox
, and the choice is supposed to filter the results available in a DataGridComboBoxColumn
(DGCBC) in a DataGrid
.
But I am at a loss at how to bind the ComboBox
SelectedItem
to the DGCBC. I did manage to have the ComboBox
filter the results of a second ComboBox
, but that logic does not seem to transfer well to the DGCBC.
What I have tried:
My ComboBox
:
<ComboBox
DisplayMemberPath="PropertyName1"
ItemsSource="{Binding Collection1}"
Loaded="{s:Action NameOfMethodToPopulateComboBox}"
SelectedItem="{Binding PropertyHolder, UpdateSourceTrigger=PropertyChanged}"/>
The PropertyHolder
is ran when an item is selected in the ComboBox
, and if it's not null, it runs the method that adds to the ObservableCollection
which is bound to the DGCBC. It looks like this:
private ClassName _currentSelectedItem;
public ClassName CurrentSelectedItem {
get { return this,._selectedItem; }
set { SetAndNotify(ref this._selectedItem, value);
if (value != null) {
FillDataGridComboBoxColumn();
}
}
}
The method, FillDataGridComboBoxColumn()
looks like this (abbreviated):
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);
This is the XAML for the DataGrid
and the DataGridComboBoxColumn
:
<DataGrid
AutoGenerateColumns="False"
ItemsSource="{Binding MyObservableCollection}">
<DataGridComboBoxColumn
SelectedValueBinding="{Binding PropertyName2, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="PropertyName2"
DisplayMemberPath="PropertyName2"
ItemsSource="{Binding MyObservableCollection}">
/>
</DataGrid>
When I debug, the DataGridComboBoxColumn
is able to get the correct number of rows - but they're just empty placeholders; blanks. If I put a break-point in the code, I see that the collection is indeed loaded with the correct values, but they're just not showing.
I am guessing I am doing something wrong with the binding for the DGCBC.
Thank you.
The DataGridComboBoxColumn
ItemSource
had to be set as a Static Resource
:
<Window.Resources>
<CollectionViewSource x:Key="MyObservableCollection" Source="{Binding MyObservableCollection}"/>
</Window.Resources>
And then, in the XAML for the DataGridComboBoxColumn
:
<DataGridComboBoxColumn
ItemsSource="{Binding Source={StaticResource MyObservableCollection}}"
DisplayMemberPath="Property2">
</DataGridComboBoxColumn>