2012年5月4日 星期五

[Windows] Basic WPF UI template

When you creating a UI for your application, usually you will make several UI element of same type, it is kind of annoying if you need to copy and paste all attributes to make those object looks the same. So in XAML programming in WPF, you can define a template for your controls.

Code snapshot:
<UserControl>
    <UserControl.Resources>
        <Style x:Key="BaseBtn" TargetType="Button">
            <Setter Property="Width" Value="80px"/>
            <Setter Property="Height" Value="80px"/>
        </Style>
        <Style x:Key="BottomRightBtn" BasedOn="{StaticResource BaseBtn}" 
                TargetType="Button">
            <Setter Property="HorizontalAlignment" Value="Right"/>
            <Setter Property="VerticalAlignment" Value="Bottom"/>
            <Setter Property="Margin" Value="10"/>
        </Style>
        <Style x:Key="BottomLeftBtn" BasedOn="{StaticResource BaseBtn}"
                TargetType="Button">
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="VerticalAlignment" Value="Bottom"/>
            <Setter Property="Margin" Value="10"/>
        </Style>
    </UserControl.Resources> 
    <Grid>
        <Button Content="BaseBtn" Style="{StaticResource BaseBtn}"/>
        <Button Content="BottomLeftBtn"
                Style="{StaticResource BottomLeftBtn}"/>
        <Button Content="BottomRightBtn"
                Style="{StaticResource BottomRightBtn}"/>
    </Grid>
</UserControl>


UserControl.Resources is a nice place to put all your styles.
Note that you need to specify the TargetType in style tag. So your style can be used on this type only.
Each Setter define a single property like width and height, which should also exist in the target type.
To use the style, just use something like Style="{StaticResource ResourceKey}" to reference them.
That how you do simple sytle in WPF XAML, probably will save you some time.

沒有留言:

張貼留言