Reputation: 1506
Ok i have made a new style for the Buttons
that i want to use in my app. The general idea is to have 10 square Button
in which i will have an Image
and under this a TextBlock
.
My problem is that i want to set my Image.Source
and my TextBlock.Text
different for each Button
.
What im doing is this :
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Border" CornerRadius="5" BorderThickness="1" Background="Gray" BorderBrush="Orange">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image Margin="0,5,0,0" Grid.Row="0" Width="25" Height="25" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<TextBlock FontSize="12"/>
</Grid>
</Border>
What should i do in order to make use of my style like this?
<Button Style="{DynamicResource MenuButtons}" Text="????" x:Name="LiveB" Source="????" Click="Live_Click"/>
Thanks in advance.
Upvotes: 0
Views: 2691
Reputation: 13057
If all you need is an image and some text, you can make it work (mis)using the button's .Tag
and .Content
:
<Style x:Key="MenuButtons" ...
...
<ControlTemplate TargetType="{x:Type Button}" >
<Border x:Name="Border" CornerRadius="5" BorderThickness="1" Background="Gray" BorderBrush="Orange">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image Width="25" Height="25" VerticalAlignment="Center" HorizontalAlignment="Center"
Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Tag}" />
<TextBlock FontSize="12" Text="{TemplateBinding Content}" Grid.Row="1" />
</Grid>
</Border>
</ControlTemplate>
...
..and then:
<Button Style="{DynamicResource MenuButtons}" x:Name="LiveB"
Content="MyText la la la..." Tag="http://programming.enthuses.me/1.png"
Click="Live_Click" />
If you need more custom content, you need to look at Konstantin Zhukov's comment and Attached Properties
.
(Why you can't just use "{TemplateBinding Tag}"
instead of "...{RelativeSource TemplatedParent}..."
? I don't know, but TemplateBinding
is generally a really fragile shortcut that doesn't always do what it's supposed to do...)
Upvotes: 2
Reputation: 30127
What you need to do is create a a class which will act as DataContext to button
Class ButtonDataContext
{
public String TextBlockText {get;set;}
public String ImageSource {get;set;}
}
then do
LiveB.DataContext = new ButtonDataContext(){TextBlockText = "text", ImageSource = "Image Path"};
in control template XAML
<Image Source="{Binding Path=ImageSource}" Margin="0,5,0,0" Grid.Row="0" Width="25" Height="25" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding Path=TextBlockText}" FontSize="12"/>
Upvotes: 1