Flat button in WPF - trigger not firing - c#

I wanted to restyle my buttons to be more flat so I have created two styles; first for ToggleButton that derives from ToolBar.ToggleButtonStyleKey and second for Buttonthat derives from ToolBar.ButtonStyleKey.
It worked great - the buttons are now toolbar-like and flat. Second thing I wanted is to have Background property to be transparent when user hovers the cursor over the control. So to achieve that I defined a simple trigger that sets the Background to Transparent on IsMouseOver event. It worked for ToggleButton, however, the same trigger didn't work for Button(the background was not affected at all).
Does anyone know why this trigger works great for ToggleButton and does not work for Button? I did expect the same behavior since both styles are from the same family.
Below is the full code.
<Window x:Class="WpfButtonsTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="FlatToggleButton" TargetType="ToggleButton"
BasedOn="{StaticResource {x:Static ToolBar.ToggleButtonStyleKey}}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Focusable" Value="False"/>
<Setter Property="Background" Value="Transparent"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Transparent"/>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="FlatButton" TargetType="Button"
BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Focusable" Value="False"/>
<Setter Property="Background" Value="Transparent"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Transparent"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<ToggleButton Style="{StaticResource FlatToggleButton}">
I am Toggle Button
</ToggleButton>
<Button Style="{StaticResource FlatButton}">
I am Button
</Button>
</StackPanel>
</Grid>
</Window>

I had a look using Snoop (a very handy program for inspecting WPF ) and it looks like the template which you're using as a basis, ToolBar.ButtonStyleKey, has a trigger which selects a solid Brush for the background of a Border element within the Button (in thise case when IsMouseOver is true).
Your local style trigger is successfully setting the background of the Button element to transparent (or rather, keeping it transparent), but the Border background is unaffected, so you'll still see the highlighting behaviour.
Border Background:
Button Background:
I think you'll have to define a ControlTemplate to get the button you're after, I've grabbed this from one of the ToolBar samples included in Kaxaml (a nice XAML editor). It's a reasonable facsimile of the Toolbar bas button style, with a few bits removed, it may behave as you want, or you might need to tweak it depending on your desired behaviour.
I've left the IsPressed trigger in place, you may want to remove it, or add additional triggers.
<Style x:Key="ToolBarButtonBaseStyle" TargetType="{x:Type ButtonBase}">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ButtonBase}">
<Border
x:Name="Border"
BorderThickness="1"
Background="Transparent"
BorderBrush="Transparent">
<ContentPresenter
Margin="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True"/>
</Border>
<ControlTemplate.Triggers>
<!-- Additional triggers removed, e.g "IsMouseOver" -->
<!-- You may not want any at all -->
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="Border" Property="Background" Value="#E0E0E0" />
<Setter TargetName="Border" Property="BorderBrush" Value="#606060" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

I see that the both FlatToggleButton and FlatButton styles already have Background as Transparent
<Setter Property="Background" Value="Transparent"/>
When the triggers is fired on IsMouseOver and set the Background again to Transparent you will not see any difference
So what you need to do is one of these options :
Change both styles so that the Background is something else than Transparent
Change the trigger so it sets the Background to something else than Transparent

Related

Why is my button style not applied when declared in the resources of another style? [duplicate]

This question already has answers here:
How do you change Background for a Button MouseOver in WPF?
(6 answers)
Closed last month.
I don't understand why this doesn't change the Background and Foreground while hovering the Button. It changes the CornerRadius of the Border tho.
ButtonStyle.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="Button" x:Key="RoundedCorners">
<Style.Resources>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="Green"/>
</Trigger>
</Style.Triggers>
</Style>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="5"/>
</Style>
</Style.Resources>
</Style>
</ResourceDictionary>
LoginView.xaml
<Button Height="50"
Width="200"
Style="{StaticResource RoundedCorners}">
LOGIN
</Button>
In WPF, an explicit Style set locally through Style={StaticResource StyleKey} takes precedence over an implicit style matched through a TargetType, as detailed here.
Hence, only the outer Style is applied to your Button because it's given a key and epxlicitly set.
To fix it, you should meger the inner Style into the keyed Style like this:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="Button" x:Key="RoundedCorners">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="Green"/>
</Trigger>
</Style.Triggers>
<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="5"/>
</Style>
</Style.Resources>
</Style>
</ResourceDictionary>
This will properly change the Foreground when you hover it. The Background will still not change, but that's an entire different problem.

WPF changing button color, with a defined style already in place

i've made some rounded buttons, using a template. hovering the button changes the colour
MainWindow
<Button Grid.Column="1" x:Name="pressbtn" Command="{Binding TypeChange}"
CommandParameter="{Binding Name ,RelativeSource={RelativeSource Self}}"
Style="{StaticResource btnBlue}" BorderBrush="MidnightBlue"
HorizontalAlignment="Stretch">Press</Button>
Style Resource
<Style TargetType="Button" x:Key="btnBlue">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#000"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="Margin" Value="5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="0,1,1,0"
CornerRadius="10">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="MidnightBlue"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
this works fine, but i'd like the button to stay on a background colour until another button is pressed, upon which it would go transparent and the other button would change colour
i have tried (where IsSelected is an integer, with each button triggering the property)
<DataTrigger Binding="{Binding IsSelected}" Value="0">
<Setter Property="Background" Value="MidnightBlue"/>
</DataTrigger>
i've also tried
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="MidnightBlue"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
it seems that any of the button events (like IsPressed) are transient, so a button press works for a brief period but wont stick. reading up about the , it appears that it doesn't work because i set the Background inline in the main Setter
<Setter Property="Background" Value="Transparent"/>
However, if i take out that Property, nothing changes
this part of XAML is a weak point (Styles, Templates), and i can't find anything in searching that helps or at least that i understand very well. Any assistance in getting the <DataTrigger> or other method to work is appreciated
If you want a "sticky" version of IsPressed, you should use a ToggleButton and bind to its IsChecked property.
An ordinary Button has no property to indicate whether it has previously been clicked or not.
You will of course also have to write some code that sets the IsChecked property back to false or true when the other Button is clicked.
If IsChecked doesn't fits your requirements, there is the Tag property that you can set to anything.

How can I change Button color via a trigger in the button?

Whats wrong with this trigger? I found it here: http://www.wpf-tutorial.com/styles/trigger-datatrigger-event-trigger/ and ive seen similar setups on SO
<Button x:Name="ColorPickerButton" Background="{Binding SelectedColor}">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Im trying to break down my spaghetti XAML and make it more readable. This is my old implementation which does work. I dont like it because it overwrites the button content and overlays a border which seems unnecessary. Also its massive
<Button x:Name="ColorPickerButton" Background="{Binding SelectedColor}">
<Button.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Bd"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="true">
<GridViewRowPresenter/>
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="BorderBrush" Value="{StaticResource ColorPickerButton.MouseOver.Border}"/>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Resources>
</Button>
Your Trigger does not work because the default Template of the button has its own trigger that changes the background brush of the root border when the IsMouseOver Property is set. This means: As long as the mouse is on top of the button, the Background-property of the button control will be ignored by its template.
The easiest way to check out the default style of your button is to: right-click at the button in the visual studio wpf designer. Click 'Edit template' -> 'Edit a copy' and select a location.
A copy of the default style is created at the specified location. You will see a trigger like this:
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
</Trigger>
On top of designer created style definition it also created the brushes that are used within the style:
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
You can either change these brushes or the Value property of the setters above to change the background when the mouse is over.
Or you create your own Template like you did in your old implementation.

WPF Button Style Template IsEnabled

i based my application on this
example
i need my own button-style (without mouseover animations etc.), so i made this in the app.xaml:
<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="Border"
CornerRadius="2" BorderThickness="1"
Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}">
<ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}" />
<Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource DisabledBorderBrush}" />
<Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
my button: <Button IsEnabled="true"/>
now if i change the button to <Button IsEnabled="false"/> my app crashes at the start with an error like: "{DependencyProperty.UnsetValue}" is not a valid value for property "BorderBrush".
what am i doing wrong?
It has to do with your static reference.
In particular, XAML parsing is very touchy on order - you have to make sure that a brush with x:Key="DisabledForegroundBrush" is referenced before the parser gets to the line in the above style - even if your style above is in the same file as the DisabledForegroundBrush.
If you don't have a brush yet for the DisabledForegroundBrush, you can either remove the line referencing it in the above code if you don't require it, or, if you want it, you can create one as follows:
<SolidColorBrush x:Key="DisabledForegroundBrush" Color="Red" />
Where you can choose the color as appropriate. Alternatively, you can choose some other kind of brush here: http://msdn.microsoft.com/en-us/library/aa970904(v=vs.110).aspx
If you have a brush you'd like to use already, then if you could provide a little more information as to where the brush is in the code base (eg is it in a resource dictionary?) and where the DisabledForegroundBrush brush is, this might help me pinpoint an actual solution / best way of ensuring the brush is referenced.
Note: an alternative if you can't ensure that DisabledForegroundBrush is parsed first is to change the StaticResource to a DynamicResource, but this isn't recommended unless the resource's link might actually change at run time (see What's the difference between StaticResource and DynamicResource in WPF? )
An easier solution:
If you just want to hard-code the style in, instead of reference the foreground brush externally, then you could change the line:
<Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/>
to:
<Setter Property="Foreground" Value="[SOME COLOR]"/>
To get rid of the need to create a separate brush object for your font.

ToggleButton Style only works on last ToggleButton

I'm trying to customize my ToggleButtons so that when checked they say 'Yes' in green and when not checked, say 'No' in red.
I've created the following style which is sitting in my Styles resource dictionary.
<!-- ToggleButtons -->
<Style x:Key="YesNoToggleStyle" TargetType="ToggleButton">
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="SpringGreen" />
<Setter Property="Content">
<Setter.Value>
<TextBlock Text="Yes"/>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsChecked" Value="False">
<Setter Property="Background" Value="Crimson" />
<Setter Property="Content">
<Setter.Value>
<TextBlock Text="No"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
This works ... sort of. If the ToggleButton is the last one of either value, then it displays correctly. All previous buttons with the same value are blank. The height was also shrinking, but I fixed that with the 'Height' Setter above the triggers. To illustrate, when a new record is being created it looks like:
and after I've clicked buttons 1, 2, and 3 and 1 again:
I originally had the style referenced from the surrounding grid:
<Grid>
...
<Grid.Resources>
<Style BasedOn="{StaticResource YesNoToggleStyle}" TargetType="{x:Type ToggleButton}" />
</Grid.Resources>
But changing that so each ToggleButton references the style individually (<ToggleButton Style="{StaticResource YesNoToggleStyle}" ... />) hasn't made a difference.
I looked at Customizing the toggle state of a toggle button in wpf, and Override ToggleButton Style where the effect is the same, but they talk about external images, and my issues is all within wpf.
I also looked at the second answer to: i want to change backcolor of toggle button when toggle button ischecked and viceversa in WPF but a) I only have the blend + sketchflow preview that comes with VS2012, and b) i'm a total noob with blend and can't get from Select the "Checked State" to Reset the Background Color instruction in the answer (plus i'd be surprised if this task requires the blend tool).
Can anyone show me what to do to get multiple ToggleButtons to use the same style properly?
This works for me. Somewhere in Dictionary1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="YesNoToggleStyle" TargetType="{x:Type ToggleButton}" BasedOn="{StaticResource {x:Static ToolBar.ToggleButtonStyleKey}}">
<Style.Triggers>
<Trigger Property="IsChecked" Value="False">
<Setter Property="Background" Value="Crimson" />
<Setter Property="Content" Value="No"/>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="SpringGreen" />
<Setter Property="Content" Value="Yes"/>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
Note, that style is based on ToolBar.ToggleButtonStyle.
<Grid>
<Grid.Resources>
<ResourceDictionary Source="pack://application:,,,/Dictionary1.xaml"/>
</Grid.Resources>
<ItemsControl ItemContainerStyle="{StaticResource YesNoToggleStyle}">
<ToggleButton />
<ToggleButton />
<ToggleButton />
</ItemsControl>
</Grid>
try to replace Content property to ContentTemplate:
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="Yes"/>
</DataTemplate>
</Setter.Value>
</Setter>
In my case I wanted to have a "Locked" ToggleButton in a common dll defined and reused across my Apps.
Here's my result, which worked for me. Maybe someone find it useful (put this in a Resourcedictionary.xaml):
<BitmapImage x:Key="LockedLock"
UriSource="/...;component/Resources/Lock_closed_16p.png" />
<BitmapImage x:Key="OpenLock"
UriSource="/...;component/Resources/Lock_open_16p.png" />
<Style x:Key="LockButton"
TargetType="ToggleButton">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Image Source="{DynamicResource OpenLock }"
Width="12"
Height="12"
Name="contentimage" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ToggleButton , AncestorLevel=1, Mode=FindAncestor }, Path=IsChecked}"
Value="True">
<Setter Property="Image.Source"
TargetName="contentimage"
Value="{DynamicResource LockedLock }" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
Credits to:
Setting Button's Content to <Image> via Styles
Setter Target Name not recognized

Categories