AgainMe AgainMe - 1 month ago 8
C# Question

ComboBox with fixed Header

I need to show a default text in my

, this text must not changed also when the user select an item of the
, 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">
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Item.Name}" />

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?


You could use a Combined Template (ref post)

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

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