Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse control template?

Tags:

wpf

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.

like image 332
Kirill Lykov Avatar asked Jan 21 '23 06:01

Kirill Lykov


1 Answers

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>
like image 94
John Bowen Avatar answered Jan 31 '23 15:01

John Bowen