Multiple item combo box with headers?

后端 未结 1 1705
闹比i
闹比i 2020-12-05 06:07

Is it possible to have \"column headers\" on a combo box bound to multiple items? For example a combo box that displays a persons name. The combo box would display John Doe.

相关标签:
1条回答
  • 2020-12-05 06:44

    Example:

    <ComboBox Name="cb" Grid.IsSharedSizeScope="True" ItemsSource="{DynamicResource items}">
        <ComboBox.Resources>
            <CompositeCollection x:Key="items">
                <ComboBoxItem IsEnabled="False">
                    <Grid TextElement.FontWeight="Bold">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition SharedSizeGroup="A"/>
                            <ColumnDefinition Width="5"/>
                            <ColumnDefinition SharedSizeGroup="B"/>
                        </Grid.ColumnDefinitions>
                        <Grid.Children>
                            <TextBlock Grid.Column="0" Text="Name"/>
                            <TextBlock Grid.Column="2" Text="Occupation"/>
                        </Grid.Children>
                    </Grid>
                </ComboBoxItem>
                <Separator/>
                <CollectionContainer Collection="{Binding Source={x:Reference cb}, Path=DataContext.Data}"/>
            </CompositeCollection>
    
            <DataTemplate DataType="{x:Type obj:Employee}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition SharedSizeGroup="A"/>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition SharedSizeGroup="B"/>
                    </Grid.ColumnDefinitions>
                    <Grid.Children>
                        <TextBlock Grid.Column="0" Text="{Binding Name}"/>
                        <TextBlock Grid.Column="2" Text="{Binding Occupation}"/>
                    </Grid.Children>
                </Grid>
            </DataTemplate>
        </ComboBox.Resources>
    </ComboBox>
    

    Note that getting the Collection-binding right is not that easy because there is neither DataContext nor VisualTree to rely on, ElementName and RelativeSource does not work, this is because CompositeCollection is just a collection, not a FrameworkElement.

    Other than that the way this is done is via Grids that have shared size columns. The DataTemplate is applied automatically via the DataType.

    screenshot

    Edit: Setting the header-ComboBoxItem's IsHitTestVisible property to False is not enough since it still can be selected using the keyboard. I now changed it to IsEnabled="False" which fades out the item a bit. You could probably re-template that item to not do that. Or if you find another way of disabling it from selection that would of course work out too.

    0 讨论(0)
提交回复
热议问题