Kirill Lykov
Kirill Lykov

Reputation: 1313

How to reuse control template?

Can I create parametrized control template, i.e. create control template which might contain different controls. For instance, I can use control template with label or with button - whatever I want in some position.

<ControlTemplate x:Key="MessageCTemplate">
<Grid …>
  <Rectangle …/>
  <Rectangle …/>
  <Rectangle …/>
  …
  <!--I want to have here button, label or whatever I want-->
  <label x:Name=”MsgLabel”>
<Grid/>

<Style x:Key="MsgStyle" TargetType="{x:Type Button}">
      <Setter Property="Opacity" Value="0.6" />
      <Setter Property="Template" Value="{StaticResource MessageCTemplate}" />
<Style/>

I don’t feel happy to write the same control templates which has only one different string in their code. Or, perhaps, I misunderstand smth and another way of avoiding copy-past exists.

Upvotes: 5

Views: 4617

Answers (1)

John Bowen
John Bowen

Reputation: 24453

What you're describing is a ContentControl. This is the base class for many common controls including Button, Label, ListBoxItem...

The idea of a ContentControl is that it can define its own layout and some UI elements and also include a placeholder where whatever is set as its Content property can be injected. There is also a HeaderedContentControl that allows for 2 placeholders for other content.

<ControlTemplate x:Key="MessageCTemplate" TargetType="{x:Type ContentControl}">
<Grid …>
  <Rectangle …/>
  <Rectangle …/>
  <Rectangle …/>
  <ContentPresenter/> <!-- This is where the content shows up -->
<Grid/>
</ControlTemplate>

<Button Template="{StaticResource MessageCTemplate}">
  <Label Content="My label"/>
</Button>

<Button Template="{StaticResource MessageCTemplate}">
  <Ellipse Fill="Orange" Width="100" Height="30"/>
</Button>

Upvotes: 11

Related Questions