Articles → WPF → Creating Your First Control Template In WPF

Creating Your First Control Template In WPF

  1. Create a WPF windows application.
  2. In the file Windows.xaml add a textbox control.
  3. <TextBox Width="150" Height="25"></TextBox>

  4. Now add an attribute Style in the control.
  5. <TextBox Width="150" Height="25" Style="{StaticResource TextBoxStyle}"></TextBox>

  6. Add a Style tag in Grid.Resources
  7. <Grid.Resources>
    	<Style TargetType="TextBox" x:Key="TextBoxStyle"></Style>

  8. Add the setter property inside the style tag. For writing control template setter property would be Template so the style tag would be
  9. <Style TargetType="TextBox" x:Key="TextBoxStyle">
    	<Setter Property="Template">

  10. 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">
				<Border CornerRadius="1" BorderThickness="0.5" BorderBrush="Black">
							<ColumnDefinition Width="Auto"></ColumnDefinition>
							<ColumnDefinition Width="*"></ColumnDefinition>
						<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>

Picture showing the output of your first control template in wpf
Click to Enlarge

Posted By  -  Karan Gupta
Posted On  -  Sunday, April 4, 2010


Your Email Id  
Query/FeedbackCharacters remaining 250