I am just wondering if I can make several button templates in WPF then ass开发者_JAVA百科ign 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:
- Button with black background, rounded corners, text display
- Button with silver background, rounded corners, text display with an image beside the text
- 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#)
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>
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}"/>
精彩评论