AgainMe AgainMe - 2 months ago 25
C# Question

ComboBox with fixed Header

I need to show a default text in my

ComboBox
, this text must not changed also when the user select an item of the
Combobox
, actually for do this I've created this structure:

<ComboBox ItemsSource="{Binding AvailableNations}" Width="160" Height="55" Margin="0, 0, 0, 15"
Text="Select Countries" IsEditable="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Item.Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>


this display as default text
Select Countries
but if I select an item the default text will disappear and the item selected will be displayed, how can I fix this?

Answer

You could use a Combined Template (ref post)

<Window.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="NormalItemTemplate" >
            <CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Item.Name}" />
        </DataTemplate>
        <DataTemplate x:Key="SelectionBoxTemplate" >
            <TextBlock>Select Countries</TextBlock>
        </DataTemplate>
        <DataTemplate x:Key="CombinedTemplate">
            <ContentPresenter x:Name="Presenter"
                   Content="{Binding}"
                   ContentTemplate="{StaticResource NormalItemTemplate}" />
            <DataTemplate.Triggers>
                <DataTrigger
                        Binding="{Binding RelativeSource={RelativeSource FindAncestor,ComboBoxItem,1}}"
                        Value="{x:Null}">
                    <Setter TargetName="Presenter" Property="ContentTemplate"
                            Value="{StaticResource SelectionBoxTemplate}" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ResourceDictionary>
</Window.Resources>
<Grid>
    <ComboBox ItemsSource="{Binding AvailableNations}"                  
              SelectedItem="{Binding SelectedNation}"
              ItemTemplate="{StaticResource CombinedTemplate}"
              Width="160" Height="55" Margin="0, 0, 0, 15" >
    </ComboBox>
</Grid>

The way it works is described in the original answer. Note that the suggested solution will only work when IsEditable is set to false, I assume that won't be a problem in your case. Second, to get the text displayed at start up I bound SelectedItem (e.g. to the first item in the collection).