Reputation: 5087
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:
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#)
Upvotes: 0
Views: 464
Reputation: 57959
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>
Upvotes: 4
Reputation: 29256
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}"/>
Upvotes: 2