WPF DataGrid ComboBox Column: Propagating Header Combobox throughout column
-
19-09-2019 - |
Question
Hey there! Here's my question:
I've got a Datagrid in WPF and I have a first column that is a DataGridComboBoxColumn.
What I'd like to do is to have a header for that column also with a combobox: altering the header with propagate throughout the column.
I can get this done visually, but when I submit the data, the list that is bound with the Datagrid does not carry the new combobox values.
<dg:DataGridComboBoxColumn SelectedItemBinding="{Binding BIBStatus}"
ItemsSource="{Binding Source={StaticResource typeStatus}}"
Width="0.20*">
<dg:DataGridComboBoxColumn.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="Built-In Bridge"/>
<ComboBox SelectedItem="{Binding BIBStatus}"
SelectionChanged="ComboBox_SelectionChanged"
ItemsSource="{Binding Source={StaticResource typeStatus}}"/>
</StackPanel>
</DataTemplate>
</dg:DataGridComboBoxColumn.HeaderTemplate>
</dg:DataGridComboBoxColumn>
In the ComboBox_SelectionChanged I have the following code:
DataGridColumn comboCol = this.gridResults.Columns[0];
for (int i = 0; i < this.gridResults.Items.Count; i++)
{
ComboBox myCmBox = (comboCol.GetCellContent(this.gridResults.Items[i]) as ComboBox);
myCmBox.SelectedValue = ((ComboBox)sender).SelectedValue;
}
When I submit the data, I submit the list that is DataContext to the Datagrid; if I change the value of the first column addressing a row at a time, i.e. clicking the cell with the combobox in each row, the values are propagated to the list in DataContext, however if I change the value of the first column by the header it does not.
Can anyone tell me what I'm missing? I'm guessing it's the way I affect each row, but I've tried SelectedValue, SelectedItem and SelectedIndex... all to no avail.
Thanks in advance...
Solution
I think I may have solved it... or at least disguised it...
DataGridColumn comboCol = this.gridResults.Columns[0];
for (int i = 0; i < this.gridResults.Items.Count; i++)
{
ComboBox myCmBox = (comboCol.GetCellContent(this.gridResults.Items[i]) as ComboBox);
myCmBox.SelectedItem = ((ComboBox)sender).SelectedItem;
}
if (this._results != null)
{
foreach (Device device in _results)
{
device.BIBStatus = (TypeStatus)Enum.ToObject(typeof(TypeStatus), ((ComboBox)sender).SelectedValue);
}
}
I tried to change only the datacontext and hope for the two-way binding to work, but it only did when I focused on each row's combobox. So I thought: "why not both ways?" As you can see, I change both each combobox's selecteditem and each device's BIB status (the datacontext part). This way I get the desired effect.
However I do not think this solution is the best one and I'm still hoping there is a way I can do this without being a scoundrel.
Any suggestions are still welcome!