views:

32

answers:

2

I am just wondering if I can make several button templates in WPF then assign to a specific button the template to be used by 'declaring' the button template name (or other method you suggest)

The button templates I am trying to create are:

  1. Button with black background, rounded corners, text display
  2. Button with silver background, rounded corners, text display with an image beside the text
  3. Button with gold background, text display with a different image beside the text

The style of the button I will generate depends on what button template I will 'call' wherein:

If selection = 1, template 1 will be used. (this will be done in C#)

+2  A: 

you can make as many button (or any other control) templates as you want to. you use the x:key="" attribute on the style to "name" your template, and to set the style on the destired button....

<Style x:Name="MyButton1">
....
</Style>

and then on your button....

use a Dynamic Resource..

<Button Style="{DynamicResource MyButton1}"/> 

or you can use a StaticResource instead

<Button Style="{StaticResource MyButton1}"/> 
Muad'Dib
@Muad'Dib: is there a way to call these button templates in C#?
eibhrum
correction: as your sentence said it should be x:Key not x:Name. And to call it from the code behind u'll have to use the FindResource("MyButton1")
dnr3
your right, it was a wee bit late in the evening. ;)
Muad'Dib
+4  A: 

One way to achieve this is with triggers. Give the button a style that chooses its template depending on the value of a property to which it binds.

I haven't put this in a XAML editor, so there might be a syntax mistake, but this is the gist:

<Style TargetType="Button">
    <Style.Setters>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <!-- default template -->
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style.Setters>
    <Style.Triggers>
        <DataTrigger Binding="{Binding SomeValue}" Value="1">
            <DataTrigger.Setters>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <!-- template when SomeValue == 1 -->
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </DataTrigger.Setters>
        </DataTrigger>
        <DataTrigger Binding="{Binding SomeValue}" Value="2">
            <DataTrigger.Setters>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <!-- template when SomeValue == 2 -->
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </DataTrigger.Setters>
        </DataTrigger>
    </Style.Triggers>
</Style>
Jay