数据网格组头中的WPF组合框

时间:2014-04-24 09:46:17

标签: wpf datagrid combobox

是否可以在数据网格组头中使用组合框为相应列的每个单元格设置一个选定的值(这个包含组合框)? 或者是否有更好的解决方案可以同时在列中设置多个组合框值?

1 个答案:

答案 0 :(得分:0)

您可以在组头中添加ComboBox,如下所示:

<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>

SelectionChanged事件处理程序如下所示:

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...
    }
}