i have button with this style:
<Style TargetType="Button" x:Key="btnStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Image x:Name="img" Source="{TemplateBinding Tag}" Margin="{TemplateBinding Margin}"
Stretch="None"></Image>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="img" Property="Source" Value="{DynamicResource imgClose_P}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="img" Property="Source" Value="{DynamicResource imgClose_H}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
As you can see i’m binding the ImageSource to the Tag property of the button.
And in the Tag property i’m binding it to a ResourceDictionary that store this bitmap:
<BitmapImage x:Key="imgClose_N" UriSource="..\AppImages\mainWindow\TopBanner\CloseButton_sN.png" />
this gives me the ability to use this “Imagebutton” all over the application with different background images and one template.
the problem is how to keep this generic approach with triggers?
i would like the IsMouseOver trigger to change the background image but to bind it to some property of the control and not to write it hard coded in the control template.
how can this be done ?
As you already suggest by calling it an “Imagebutton”, you may derive from
Buttonand define some image properties to bind to, e.g.BackgroundImage,MouseOverImage, etc.An alternative to deriving from
Buttonwould be to use attached properties to set the images and bind to those in your style, but these attached properties would also have to be defined somewhere, which doesn’t make it simpler.Here’s an example for the first solution:
and an appropriate style below. Note that this style also has a ContentPresenter for the button’s content, and that it uses regular bindings with
RelativeSource={RelativeSource TemplatedParent}instead of TemplateBindings. These are evaluated at runtime.You would have to define or replace the XAML namespace
localwith a mapping to the namespace/assembly that contains the classImageButton.The button could then be use like this: