简体   繁体   中英

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 eg the ContentControl.

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM