Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to add a Label to the WPF ComboBox control

This code is becoming more common in my application:

<StackPanel Orientation="Vertical">
    <Label Content="_ComboBox Caption" 
           Target="comboBox" 
           Margin="0" 
           Padding="5,5,5,1" />

    <ComboBox  x:Name="comboBox"
                Width="72"
                Margin="5,0,5,5"
                Padding="5,1,5,5"
                SelectedItem="{Binding ComboSelectedItem}"
                ItemsSource="{Binding ComboSourceList}" />
</StackPanel>

It renders me a Captioned ComboBox.

I would like to make me a custom control that is a ComboBox that exposes the Label's content and then sets the other properties up. Something that could be used like this:

<Controls:CaptionedComboBox  x:Name="comboBox"
                             Width="72"
                             LabelContent="_ComboBox Caption"
                             SelectedItem="{Binding ComboSelectedItem}"
                             ItemsSource="{Binding ComboSourceList}" />

However, I looked into making a custom control and there is a daunting amount of styling that is needed.

Is there a way to take what I have above and end up doing something like this?

<StackPanel Orientation="Vertical">
    <Label Content="{Binding TemplateLabelContent}" 
           Target="{Binding ControlName}" 
           Margin="0" 
           Padding="5,5,5,1" />

    <InheritedComboBoxStuff/>

</StackPanel>

I know that will not work. But my point is that is seems silly that I have to re-style the whole ComboBox just to add a label above it.

like image 420
Vaccano Avatar asked Sep 16 '25 22:09

Vaccano


1 Answers

You can make a template for that

  <ControlTemplate x:Key="ComboWithHeader" TargetType="ContentControl">
        <StackPanel Orientation="Vertical">
            <Label Margin="0"
                   Content="{Binding ComboBoxHeader}"
                   DataContext="{TemplateBinding DataContext}"
                   Padding="5,5,5,1"
                   Target="comboBox" />

            <ComboBox x:Name="comboBox"
                      Width="72"
                      Margin="5,0,5,5"
                      DataContext="{TemplateBinding DataContext}"
                      ItemsSource="{Binding ComboSourceList}"
                      Padding="5,1,5,5"
                      SelectedItem="{Binding ComboSelectedItem}" />
        </StackPanel>
    </ControlTemplate>

And then whenever you want to use combo with header, just use

<ContentControl Template="{StaticResource ComboWithHeader}" DataContext="{Binding ComboBoxViewModel}" />
like image 163
Sebastian Ðymel Avatar answered Sep 19 '25 13:09

Sebastian Ðymel