Shady Atef Shady Atef - 1 month ago 12
C# Question

WPF Combo box collection container displayed text

I use CompositeCollection & CollectionContainer to provide default value for a combo box, but the problem is actual data is displayed as the class full path.

Is there a way to select a field in the class to represent it. So instead of

StMaryChurchAttendance.Models.Groups
, It will show a string property

Here is the xmal

<StackPanel Orientation="Horizontal" DataContext="{Binding SelectionBarDataContext}" Name="SearchPanel">
<Label>Group : </Label>
<ComboBox Name="SelectionBarGroupsComboBox">
<ComboBox.Resources>
<CompositeCollection x:Key="CompositeCollection">
<CollectionContainer Collection="{Binding Source={x:Reference SearchPanel}, Path=DataContext.Groups }" />
</CompositeCollection>
</ComboBox.Resources>
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem Name="AllGroupItem" IsSelected="True">All Groups</ComboBoxItem>
<CollectionContainer Collection="{Binding Source={StaticResource CompositeCollection}}" />

</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
</StackPanel>


enter image description here

Answer

Usually, this works:

<ComboBox  
    DisplayMemberPath="WhateverPropertyYouWant"
    Name="SelectionBarGroupsComboBox">

Replace WhateverPropertyYouWant with the property you want to display -- some property of StMaryChurchAttendance.Models.Group. Don't use a binding. Just type the name of the property between the quotation marks.

But you've got a mix of different stuff in there, so it's not going to work this time. Here's another option: Create an implicit DataTemplate for your Group class, that's only visible within the ComboBox. The ComboBox will use that to display Groups, without affecting anything else.

<ComboBox  
    Name="SelectionBarGroupsComboBox">
    <ComboBox.Resources>
        <CompositeCollection x:Key="CompositeCollection">
            <CollectionContainer Collection="{Binding Source={x:Reference SearchPanel}, Path=DataContext.Groups}" />
        </CompositeCollection>

        <DataTemplate 
            xmlns:models="clr-namespace:StMaryChurchAttendance.Models"
            DataType="models:Group">
            <TextBlock Text="{Binding Name}" />
        </DataTemplate>
    </ComboBox.Resources>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Name="AllGroupItem" IsSelected="True">All Groups</ComboBoxItem>
            <CollectionContainer  Collection="{Binding Source={StaticResource CompositeCollection}}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>
Comments