Saturday 20 September 2014

Types of Templates in WPF


  1. Control Template

    This template specifies the appearance of a Control; if a control does not have a Control Template, the Control will not appear in your application.
    For Example - When you will add the template defines as below to your application as a resource then all the buttons in the application will appear as ellipses but will still function as buttons.
    1. <Style TargetType="Button">
    2. <!--Set to true to not get any properties from the themes-->
    3. <Setter Property="OverridesDefaultStyle" Value="True"/>
    4. <Setter Property="Template">
    5. <Setter.Value>
    6. <ControlTemplate TargetType="Button">
    7. <Grid>
    8. <Ellipse Fill="{TemplateBinding Background}"/>
    9. <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
    10. </Grid>
    11. </ControlTemplate>
    12. </Setter.Value>
    13. </Setter>
    14. </Style>
  2. Data Template

    This template specifies a group of characteristics for how data should be displayed. This template is particularly useful when you are binding an ItemsControl such as a ListBox to an entire collection.
    For Example – The Template defined as below, is used to display the items of a ListBox. The data template contains TextBlock controls that bind to the FirstName, LastName, and Address properties.
    1. >Grid>
    2. >Grid.Resources>
    3. >src:Customers x:Key="customers"/>
    4. >/Grid.Resources>
    5. >ListBox ItemsSource="{StaticResource customers}" Width="350" Margin="0,5,0,10">
    6. >ListBox.ItemTemplate>
    7. >DataTemplate>
    8. >StackPanel Orientation="Horizontal">
    9. >TextBlock Padding="5,0,5,0"
    10. Text="{Binding FirstName}" />
    11. >TextBlock Text="{Binding LastName}" />
    12. >TextBlock Text=", " />
    13. >TextBlock Text="{Binding Address}" />
    14. >/StackPanel>
    15. >/DataTemplate>
    16. >/ListBox.ItemTemplate>
    17. >/ListBox>
    18. >/Grid>

No comments:

Post a Comment