I’m working on a WPF application. I have a Resource Dictionary in which I wrote custom Styles for the ToolTip and for the Button. Actually, for the button i’ve made two styles.
One of them, has included an image to appear to the left of the content in the buttoon.
<Style x:Key="ButtonImageStyle" TargetType="{x:Type Button}">
........
<TextBlock Margin="5.25,2.417,5.583,5.25" Foreground = White />
<Image x:Name="ButtonImage" Source="/MyProject;component/Images/icoMainMenu01.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="-100,0,0,0" Width="16" Height="16"/>
.... </Style
Now, in the MainWindow.xaml i have the following:
<Button Style="{DynamicResource ButtonImageStyle}" x:Name="JustButton" Click="JustButton_Click" Height="50" ToolTip="Press for 1" Content="1" Margin="310,282,400,238" />
I want to be able to change that Image. I will have like 8 buttons and I want each button to have a different image associated with it.
Do you guys have any idea ?
Thanks!
There are various options, from (ab)using properties like the
Tagto subclassing or composition in aUserControl, you could also create an attached property.The cleanest would probably be subclassing though, then you can create a new dependency property for the
ImageSourceto be used which you then can bind in the default template using aTemplateBinding.To do the subclassing you can use VS, from the new items choose
Custom Control (WPF), this should create a class file and add a base-style to a themes resource dictionary which usually is found inThemes/Generic.xaml. The class would just look like this:Now the theme would be more complicated, you can just copy one of the default templates for a button and paste it into the the default style. Then you only need to add your image somewhere but with this binding:
When you use this control you will then no longer need to reference a style, as everything is in the default style, there is now a property for the image:
(To use the
Tagyou would just stick with the normal button and use a TemplateBinding to the tag and set the Tag of the buttons to the URL)I forgot to mention another possiblity which uses dynamic resources, it’s a bit verbose but very simple, see this answer of mine for an example.