Articles → WPF → Creating Your First Control Template In WPF
Creating Your First Control Template In WPF
- Create a WPF windows application.
- In the file Windows.xaml add a textbox control.
<TextBox Width="150" Height="25"></TextBox>
- Now add an attribute Style in the control.
<TextBox Width="150" Height="25" Style="{StaticResource TextBoxStyle}"></TextBox>
- Add a Style tag in Grid.Resources
<Grid.Resources>
<Style TargetType="TextBox" x:Key="TextBoxStyle"></Style>
</Grid.Resources>
- Add the setter property inside the style tag. For writing control template setter property would be Template so the style tag would be
<Style TargetType="TextBox" x:Key="TextBoxStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate></ControlTemplate>
</Setter.Value>
</Setter>
</Style>
- In the ControlTemplate tag I am adding a border and inside the border there is a Grid and finally inside the grid there is an image and textbox. So the final code would be.
<Style TargetType="{x:Type TextBox}" x:Key="TextBoxStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border CornerRadius="1" BorderThickness="0.5" BorderBrush="Black">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Image Source="images\Emoticon.gif" HorizontalAlignment="Left" Grid.Column="0"></Image>
<TextBox BorderThickness="0" Margin="0,0,1,0" HorizontalAlignment="Stretch" BorderBrush="Transparent" Grid.Column="1" VerticalContentAlignment="Center"></TextBox>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Click to Enlarge