Question

Is it possible to use a combobox in a datagrid group header to set a selected value for each cells of the appropriate column (this one contains comboboxes)? Or is there any better solution to set multiple combobox values in a column at the same time?

Was it helpful?

Solution

You can put a ComboBox in the group header like this:

<DataGrid.GroupStyle>
    <GroupStyle>
        <GroupStyle.ContainerStyle>
            <Style TargetType="{x:Type GroupItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type GroupItem}">
                            <Expander>
                                <Expander.Header>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="{Binding Path=Name}" VerticalAlignment="Center" />
                                        <TextBlock Text="{Binding Path=ItemCount}" Margin="5,0,2,0" VerticalAlignment="Center" />
                                        <TextBlock Text="Items" VerticalAlignment="Center" />
                                        <ComboBox Margin="10,0" SelectionChanged="ComboBox_SelectionChanged">
                                            <ComboBoxItem Content="1" />
                                            <ComboBoxItem Content="2" />
                                            <ComboBoxItem Content="3" />
                                        </ComboBox>
                                    </StackPanel>
                                </Expander.Header>
                                <ItemsPresenter />
                            </Expander>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </GroupStyle.ContainerStyle>
    </GroupStyle>
</DataGrid.GroupStyle>

The SelectionChanged event handler looks something like this:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DependencyObject dependencyObject = sender as DependencyObject;

    // Walk up the visual tree from the ComboBox to find the GroupItem.
    while (dependencyObject != null && dependencyObject.GetType() != typeof(GroupItem))
    {
        dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
    }

    GroupItem groupItem = dependencyObject as GroupItem;
    CollectionViewGroup collectionViewGroup = groupItem.Content as CollectionViewGroup;

    // Iterate the items of the CollectionViewGroup for the GroupItem.
    foreach (object item in collectionViewGroup.Items)
    {
        // Your logic for changing values here...
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top