Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combining commonly used WPF-Controls for Reuse

I keep repeating the same code over and over:

<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
    <StackPanel Orientation="Vertical">
        <Label Content="Content 1" VerticalAlignment="Center" HorizontalAlignment="Center"/>
        <ComboBox Style="{StaticResource CustomComboBox}"/>
    </StackPanel>
</StackPanel>

It is always some combination of an Input-Control (TextBox, ComboBox, …) and a Label.

I have scouted this Thread, but unfortunately the second answer relies on Bindings; I’d like to define the Content of the Label and the ComboBox-Bindings inside e.g. the ContentControl.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My attempt looks like this (inside MainWindow.xaml):

<Window.Resources>
    
    <ControlTemplate x:Key="ComboWithHeader" TargetType="ContentControl">
        <StackPanel Orientation="Vertical">
            <Label Width="120" Height="25" Content="{TemplateBinding Content}"/> 
            <ComboBox Width="120" Height="25"/>
        </StackPanel>
    </ControlTemplate>
    
</Window.Resources>

<Grid>
    <ContentControl Content="My Header" Template="{StaticResource ComboWithHeader}"/>
    
</Grid>

However, I couldn’t set the Content, nor does it look quite appealing.
The ContentControl occupies the whole Window, and Content isn’t visible.

>Solution :

A ContentControl should use a ContentTemplate:

<Window.Resources>

    <DataTemplate x:Key="ComboWithHeader">
        <StackPanel Orientation="Vertical">
            <Label Width="120" Height="25" Content="{TemplateBinding Content}"/>
            <ComboBox Width="120" Height="25"/>
        </StackPanel>
    </DataTemplate>

</Window.Resources>

<Grid>
    <ContentControl Content="My Header" ContentTemplate="{StaticResource ComboWithHeader}"/>
</Grid>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading