Reputation: 373
I have a Button
Style:
<Style TargetType="{x:Type Button}" x:Key="myBtnStyle">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
x:Name="myTextBlock" />
<Rectangle Grid.Row="1"
x:Name="myRectangle" />
</ close everything>
Is there any way to pass in values (Text
, and Fill
to myTextBlock and myRectangle respectively) when I assign the style to the button?
<Button Style="{StaticResource ResourceKey=myBtnStyle /*assign Text and Fill here?*/ }"
Click="myBtn_Click" />
If I can't assign it there, then where can I assign it?
Upvotes: 1
Views: 89
Reputation: 13017
It would probably be easier to use Button.Template
(ControlTemplate
) rather than Button.ContentTemplate
(DataTemplate
) here:
WPF: Button Template vs ContentTemplate
Difference between Control Template and DataTemplate in WPF
Then you can use TemplateBinding
on properties that a button already has, for example use Button.Content
for the Text and Button.Background
for the Fill.
<Style TargetType="{x:Type Button}" x:Key="myBtnStyle" >
<Setter Property="Template" >
<Setter.Value>
<ControlTemplate TargetType="Button" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{TemplateBinding Content}" />
<Rectangle Grid.Row="1" Fill="{TemplateBinding Background}" />
</ close everything>
Usage:
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text here.." Background="Blue"
Click="myBtn_Click" />
EDIT:
Template with image, (mis)using Button.Tag
:
...
<ControlTemplate TargetType="Button" >
...
<!--For some reason, the shorthand "{TemplateBinding Tag}" doesn't work here,
so we must use the longer "RelativeSource" syntax in this binding:-->
<Image Grid.Row="1"
Source="{Binding RelativeSource={RelativeSource TemplatedParent},
Path=Tag}" />
...
Usage:
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text 1" Tag="http://programming.enthuses.me/1.png" />
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text 2" Tag="/MyIcons/Icon01.png" />
Upvotes: 1
Reputation: 2031
As mentioned, you can use TemplateBinding
which is a shorthand for writing:
{Binding Path=Content, RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type Button}}}
In your case, the code would be:
<TextBlock Text="{TemplateBinding Content}" />
<Rectangle Width="50" Height="10" Fill="{TemplateBinding Button.Background}" />
Usage:
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text here.." Background="Blue"
Click="myBtn_Click" />
Upvotes: 0