I am a bit new to WPF and XAML, just learning now.
I found a quick-n-dirty code by some previous developer:
<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
<Border Name="buttonBorder" Background="{TemplateBinding Background}">
<Border.Effect>
<DropShadowEffect Opacity="0.0" />
</Border.Effect>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="buttonBorder" Property="Effect">
<Setter.Value>
<DropShadowEffect Opacity="0.8" />
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsMouseCaptured" Value="true">
<Setter TargetName="buttonBorder" Property="Effect">
<Setter.Value>
<DropShadowEffect Opacity="0.8" Direction="135"
ShadowDepth="3" BlurRadius="1" />
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="buttonBorder" Property="Background">
<Setter.Value>
<ImageBrush ImageSource="{Binding Path=Tag, RelativeSource={RelativeSource TemplatedParent}}" />
</Setter.Value>
</Setter>
<Setter TargetName="buttonBorder" Property="Effect">
<Setter.Value>
<DropShadowEffect Opacity="0.0"/>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
Basically it is just a template for a button with a basic mouseover effect and the image for disabled state bound to Tag (seems an ugly solution).
I want to create a custom button which works pretty the same, but I want to expose two custom properties: NormalImage and DisabledImage. Those properties should be of type string not Uri. I want to use the path to image just “apply.png” and not “pack://application:,,,/Resources/Apply.png”.
I guess, to have such custom properties I need a UserControl with dependency properties?
Basically, I want to use the button as follows:
<MyImageButton NormalImage="apply.png" DisabledImage="apply_disabled.png"/>
Maybe NormalImage/DisabledImage will be bound to something later but that’s unlikely.
I could not find any example which implements such a basic button with custom properties, there are only some fancy buttons and controls online. Maybe I am just using incorrect keywords…
Could anyone point me to the right article or throw some simple piece of code to play with?
WPF is so complicated for beginners, sometimes it just does not work as expected, for example I still do not understand why I can add Trigger tag to ControlTemplate, but I cannot add Trigger tag straight to UserControl…
You could also use a
UserControlwhich is a bit messy since your button will be encapsulated, would look something like this:Xaml:
Code behind:
Example usage:
(Note that the current namespace is
Test, you might want to change that; Also i set a fixed size on the internal button, which you might want to remove, just make sure to set the size somewhere since i think it will not use any space at all if you don’t.)