Any examples of a rich visual behaviour WPF button? - wpf

I am looking for an example of a customized WPF button.
Ideally in a liked Blend/VS2013 configuration, i.e. a VS2013 test solution that includes a button project that can be edited in Blend for VS2013.
The button should have a visual appearance that makes it clear what state it is in, i.e.
Normal = default
MouseOver = inner glow
Pressed = smaller size / smaller shadow
ToggledOn = outer glow
Disabled = grayed out
Given such an example I could then just tweak the visual appearance of the states using Blend.
And on the application side I want to just instantiate the button, associate the style, and set properties for BackgroundColor, image/icon, text label, width, height.
I seems that using a ControlTemplate style is the recommended way of doing this, rather than sub-classing, see MSDN.
The three key issues seem to be:
how to setup the VS2013/blend project structure to use both interchangeably on a single set of source files
how to compute relative sizes in the ControlTemplate, i.e. what is the syntax for
Width = Button.Width x 1.1 to set a glow extend relative to the actual button size that is not in the template, but to be defined on the client application UI design.
how to compute relative colors from the base color of the button, i.e. what is the WPF XAML syntax for GradientStop Color = Button.BackgroundColor x 80% + White x 20%
This should be a very common need, but Google was not helpful in finding anything like the above.
Any help with any one of the three key issues would be greatly appreciated.

Your requirements do not require defining a new ControlTemplate and can be achieved with a Style with Triggers, e.g.:
<Grid>
<Grid.Resources>
<Style TargetType="Button">
<Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX="0.75" ScaleY="0.75"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<Button Content="Click Me!" />
</Grid>
The Style can be accessible anywhere in the application if defined in your App.xaml Resources and given an x:Key
Using ScaleTransform's ScaleX and ScaleY are relative values.
You will need your own IValueConverter then bind the target color to a source color using your converter.

Related

Replace Foreground color of all controls

To switch to dark theme I am currently switching merged dictionaries. DarkTheme.xaml contains:
<SolidColorBrush x:Key="GlobalTextColor" Color="#FFFFFF" />
<SolidColorBrush x:Key="GlobalBackColor" Color="#000000" />
and then each control template has something like
Foreground="{DynamicResource GlobalTextColor}"
Is there a more elegant way to replace all text at once like High Contrast theme does (without other style changes of that theme) or promised performance penalty of DynamicResource bindings?
Something like this?
<Style x:Key="Highlight" TargetType="{x:Type Control}">
<Setter Property="Foreground" Value="Red"/>
</Style>
This would set all the foregrounds on each control to red.
This way you can reference it as a static resource.
Source: Can you define multiple TargetTypes for one XAML style?
Or another link here: How to target all controls (WPF Styles)
You can right click on the project from the solution explorer(in visual studio) and select open in blend.Then apply the style the needed parts and you can save it there.You can open another page or and add those styles or you can add it to the same page attributes just selecting the attribute and giving it the saved style.

Combobox background not being applied in windows 8

I am a little confused with wpf themes. I would like to have the wpf screens look the same on Vista, Windows 7 and Windows 8. So I have styled the components accordingly and they don't pose problems except when run on Windows 8. For example I have a combobox and I am changing its default background in xaml like this.
<Style TargetType="{x:Type ComboBox}" >
<Setter Property="FontStyle" Value="Normal"/>
<Setter Property="Height" Value="24" />
<Setter Property="Background" Value="{StaticResource GradientButtonBackgroundBrush}"/>
</Style>
The combobox Background property has no effect in windows 8 and all I get is a flat rectangle with a arrow on right (the default windows 8 combobox, which is rather poorly designed!).
So, my question is that how do I get the combobox look the same on all version of windows. I tried adding windows Aero theme in my App.xaml like below, but it has no effect on the combobox display. Here is how I added Aero theme
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/PresentationFramework.Aero;component/themes/aero.normalcolor.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
There is also another doubt regarding themes. I am building the wpf application on a windows 7 machine, which by default (I believe) has Aero Theme set. So, all my styles are based on the Aero theme when viewed on Windows 7 machine. What happens if I run the application on say XP. Then do I need to add an entry for the resource dictionary (Aero theme) in App.xaml as listed in code above?
I know my question is a bit vague, but believe me, I am really confused with default themes of wpf on different Windows versions.
EDIT:
I still can't get combobox to style according to my needs. The combobox still appears like a gray rectangle.
Here is what I did. I downloaded the Aero.NormalColor.xaml from microsoft's site and included in themes folder of application. Then I added the following in App.xaml
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Themes/Aero.NormalColor.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
Then I Compiled the application and deployed on Windows 8. Still the same combobox as was shown previously. Note that all other elements get styled properly according to the theme. I did the same with Luna.Metallic.xaml and every element gets styled except the ComboBox.
I believe that when I load a particular theme, which defines styles with ControlTemplate, then it should be picked by wpf. I am confused as to why only the ComboBox even after giving it a Aero (or Luna) Control Template doesn't change its appearance. Any ideas ?
EDIT-2
Screen shot of combobox appearance on Windows 8
Well the ComboBox clickable area is actually a ToggleButton
and if you look at the Style for that ToggleButton in Windows-8, you see something like:
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border x:Name="templateRoot"
Background="{StaticResource ComboBox.Static.Background}"
BorderBrush="{StaticResource ComboBox.Static.Border}"
BorderThickness="{TemplateBinding BorderThickness}"
SnapsToDevicePixels="true">
...
As you can see from above, Background used is not a {TemplateBinding Background} but {StaticResource ComboBox.Static.Background}. Hence why you see no effect when you set the Background property in Windows-8 for that ComboBox
If your looking to carry a Style across the different OS Versions(Without having to backtrack and keep checking if new versions screwed up your over-rides), simple rule is Create it yourself.
Create a Style and set it to be applied by TargetType and without a Key to get applied automatically. That way in any OS it's your Style that gets used and not the default underlying one.
This thus guarantees your code run's as you expect on every single OS. Base your Style on the default's of any OS and tweak it to your heart's content.
side-note:
From a usability POV giving the user a Windows-7 ComboBox in an app that run's on Windows-8 is not very nice(unless your entire app looks like a Windows-7 app which is even worse). Your expecting the user to get used to your app's Style's and forget what he's used to from every other app he uses in his OS that use default Styles based on OS. If you have specific reasons for doing so, go ahead but do consider the implications.
Just for example you stated the Windows-8 Style is something your not a fan of, well I'm the opposite. I actually do like the Windows-8 clean and simple look. No distractions to the UserExperience with flashing gradients and things that throw you off the content your putting in front of them. This is an argument that goes on forever. Just be warned abt what the end-user expects and thinks than just what you think is good while writing your program.
Update:
Firstly comment on the relevant answer please. Your answer and your comment update has no relation.
Ok and as for your question edit, what you tried has not worked in windows-8 because PresentationFramework.Aero.dll does not exist in Windows-8 which is what holds Aero.NormalColor.xaml. In Windows-8 your options are PresentationFramework.Aero2.dll which is default and PresentationFramework.AeroLite.dll which I think is used by Windows Server 2012(Not Sure)
Try to compile your program on Windows-8 and you'll see it does not even want to compile.
You'll have to explicitly add a reference to PresentationFramework.Aero and also PresentationUI(which i think is part of .net3) to your project.
Then you'll have to edit your Aero.NormalColor.xaml to something like:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:theme="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
xmlns:ui="clr-namespace:System.Windows.Documents;assembly=PresentationUI">
...
^^ we explicitly state the assembly for Aero Theme. I don't use Windows-7 so Am not sure if that's all that's needed. but you can give that a try.
Try to compile your code in Windows-8 to make sure it will work fine on Windows-8
Finally, after hours of frustration, I came accross an explanation post here. Scroll for the LONG ANSWER. It explains exactly the scenario I have been facing particularly Aero style not getting applied to my Combobox. The link explains very well why we need to add a BasedOn attribute to every element that we style if we dont want the default OS style being picked up. So adding this BasedOn for the Combobox got it working for me.
<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
Now the Aero theme style is used for the combobox. As #Viv pointed out it may also require copying of PresentationFramework.Aero.dll and PresentationUI.dll to the windows 8 machine as they are not supplied with the OS.
Thanks,
Nirvan
I did a bit of a hack on the built-in template. Not the cleanest solution, but removes the headache of having to roll my own template. The code behind basically binds the built-in template border's properties with the combo box's properties.
<Style TargetType="ComboBox">
<Setter Property="Border.Background" Value="White"/>
<EventSetter Event="Loaded" Handler="ComboBox_Loaded"/>
<Style.Triggers>
<Trigger Property="IsReadOnly" Value="True">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="{StaticResource ResourceKey=FocusedControlBackcolorBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource ResourceKey=FocusedControlBorderBrush}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="{StaticResource ResourceKey=FocusedControlBorderBrush}"/>
</Trigger>
</Style.Triggers>
</Style>
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
var comboBox = sender as ComboBox;
var toggleButton = comboBox.Template?.FindName("toggleButton", comboBox) as ToggleButton;
var border = toggleButton?.Template.FindName("templateRoot", toggleButton) as Border;
if (border != null)
{
Binding b = new Binding("Background");
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ComboBox), 1);
BindingOperations.SetBinding(border, Control.BackgroundProperty, b);
b = new Binding("BorderBrush");
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ComboBox), 1);
BindingOperations.SetBinding(border, Control.BorderBrushProperty, b);
}
}
In Response to #Viv
#Viv, I feel that your answer was very clear, but somehow your views/suggestions aren't digestable to me and I will briefly mention why
Your Suggestion
If your looking to carry a Style across the different OS Versions(Without having to backtrack and keep checking if new versions screwed up your over-rides), simple rule is Create it yourself.
It seems impracticable. The very idea of themes is creation of consistent look for all elements in the application and accross all platforms. So, if I use a particular theme provided by the framework, no matter what, I should be able to achieve a satisfactory level of consistency, atleast on major current platforms. Above all, not every one has the expertise to create all the styles and templates from scratch. The concept of themes should be,
"The framework provider is providing the themes that will work well for normal scenarios and if anyone wishing to roll out his themes he is welcome to do so".
Instead here the concept seems like
"The framework provider is providing theme and it is not guranted that it will be consistent and work without breaking. So always roll out your themes"
Your quote
As you can see from above, Background used is not a {TemplateBinding Background} but {StaticResource ComboBox.Static.Background}. Hence why you see no effect when you set the Background property in Windows-8 for that ComboBox
I don't know whose idea it was to make a template that way! Must be out of his minds or I am too dumb to understand the advantages. Just imagine that I am using some Blue colored theme in my application and tommorrow, on Windows 9, somebody defines a Red as {StaticResource ComboBox.Static.Background}. So, guess what, I have a fancy window screen now with all my elements themed "Blue" and only the combobox's appear "Red". I mean the very idea of theme is broken here!
Your side note
Just for example you stated the Windows-8 Style is something your not a fan of, well I'm the opposite. I actually do like the Windows-8 clean and simple look.
My combobox looks like a disabled button and I couldn't even change its background! The buttons don't look like they are clickable! Any way as you said this is a personal choice, ofcourse.
My Conclusion
I will wait for some time if some one has any suggestions on how I get the combobox working on windows 8. Your answer brings forward the truth, so I would be happy to mark it a correct if I don't get any alternative solution.
Nirvan
The newer template has a Grid->ToggleButton->Border with a hardcoded background colour which does not respect any background styles. Based on the answer from #Matstar I made a way to sync the background colour across.
You can still set the binding to background colour and the code will pick this up and reapply this when needed:
<ComboBox ItemsSource="{Binding Values}" x:Name="Cbo2"
Background="{Binding Path=SelectedValueBgColor}" ... />
Then in xaml.cs
cbo.Loaded += (sender, args) =>
{
var comboBox = sender as ComboBox;
if (comboBox != null)
{
var toggleButton = comboBox.Template?.FindName("toggleButton", comboBox) as ToggleButton;
var border = toggleButton?.Template.FindName("templateRoot", toggleButton) as Border;
if (border != null)
{
var existing = BindingOperations.GetBinding(comboBox, BackgroundProperty);
BindingOperations.SetBinding(border, BackgroundProperty, existing);
}
}
};
Make sure your background binding never returns null
If you have no meaningful value return transparent or white or some other default. If binding to a background that returns null the combobox will stop working.
Make sure you notify property changed on your background binding if it needs refreshing when an event happens.

wpf combobox trigger for Validation.HasError

I've looked around, but can't specifically find my issue. I know that the default "Error" handling within WPF puts an "Adorner" around controls in case there are any errors based on IDataErrorInfo or Validataion rules failing a given control. That's all good and fine, however, with a tabbed page interface, if any controls are so flagged as invalid, they are properly adorned in red border. However, as soon as you go from tab page 1 to 2 and back to 1, all the adorners are gone (bad). This was already asked, and solution accepted, but was looking for a better alternative.
So, I went to my "Themes" declaration, and for the textbox control, I just said to set the entire background color of the control to red and not just the border. Without any fancy forced triggering via Notify on Property Changed, if I swap between pages, the red background of the entire textbox remains constant.
Now, on to the combobox control. For those who have customized their own, or even looked into the default MS version of the control, its actually a clustered mess of controls, grids, columns, buttons, etc to make the magic of combobox work. In brief...
ControlTemplate
Grid (two columns, one for text display of chosen, second column for the drop-down arrow)
Border spanning both columns
Path ( line drawing / glyph for the drop-down image for combobox )
ControlTemplate TargetType Textbox (as part of the entire combobox set)
Border specifically "PART_ContentHost"
ControlTemplate of combobox
Grid
Toggle Button
Dropdown exposed showing list
other triggers..
Finally, the main ComboBox declaration which is templated by above components.
Anyhow, I can't for the life of me get this. In the "Toggle Button" area of the combobox declaration, I have a trigger to change the background to an OBVIOUS off color for proof of testing the trigger working and in the right location within the ControlTemplate declarations.
So, knowing this is the correct place within the combobox declarations, I want to supersede the green background color with red if there's an error with the data. I KNOW the overall "Validation.HasError" is properly getting triggered as the native error handler shows. No matter how / where within the template I try to change the background color to red, it does NOT work. I've even tried doing DataTriggers, using converters, trying multiple properties, but it appears not to be cooperating.
Any suggestions? This is getting really annoying.
FINALLY, got it... and not as obvious as I would have guessed. Anyhow, here's what I've found. If you went with a sample from Microsoft's template of the combobox, they first provide the overall two-column "ToggleButton" declaration
<ControlTemplate TargetType="ToggleButton"
x:Key="baseComboBoxToggleButton" >
... blah blah...
</ControlTemplate>
Then, the declaration for the "Display Value" of the combobox
<ControlTemplate TargetType="TextBox" x:Key="ComboBoxTextBox" >
<Border x:Name="PART_ContentHost" Focusable="False"
Background="{TemplateBinding Background}" />
</ControlTemplate>
Then, tie them together as one Combobox "wrapper" declaration
<ControlTemplate TargetType="ComboBox" x:Key="ComboBoxGridControlTemplate" >
<Grid x:Name="GridComboWrapper">
<!-- This is the dropdown button that POINTS TO THE "baseComboBoxToggleButton at the top -->
<ToggleButton Name="ToggleButton"
Template="{StaticResource baseComboBoxToggleButton}"
Grid.Column="2" Focusable="false"
IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay,
RelativeSource={RelativeSource TemplatedParent}}"
ClickMode="Press" >
</ToggleButton>
...
rest of the content presenter,
EDIT(able) textbox area,
popup area of combobox when in drop-down mode
</Grid>
<ControlTemplate.Triggers>
<!-- PUT THE VALIDATION CHECK HERE -->
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
<!-- THIS IS THE CRITICAL COMPONENT... I HAD TO EXPLICITLY TELL
The TagetName as the "ToggleButton" and change ITs Background property
and it now works -->
<Setter TargetName="ToggleButton" Property="Background"
Value="{StaticResource BrushDataInvalidBorder}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
So, now it works as intended and doesn't loose any adorner just because the active page on a given form changes and clears it... its static to each individual control as expected... Wow... what a PITA this one was.
Hope it helps someone ELSE in the future from excessive head banging against a wall while learning this nested level of stuff.

WPF Menu Items Styles

I have an application resource of the following
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{DynamicResource windowTextBackColor}"/>
<Setter Property="Foreground" Value="{DynamicResource windowsTextForeColor}"/>
</Style>
So all the text blocks in my application should assume those colours.
However the Menu and its containing MenuItems on my Main Window does not take these colours?
I have to do the XAML
for it to assume those colours, Is there a reason why setting a style that targets Text blocks does not work?
Thanks
I think you have to style the menu and menuitems separately. A MenuItem is a HeaderedContentControl, and its Header property is not a TextBlock, but an object, so it wouldn't be affected by a style for TextBlock.
You might also try changing that style to target Control instead of TextBlock. (Control is where Foreground and Background are defined.) I can't say for sure that it'll work, but if it does, it'll make every Control (TextBlocks, MenuItems, Buttons...) have those background and foreground colors.
Also, you might consider using BasedOn so that you can "inherit" the styles. If you don't, then styles defined farther up the hierarchy won't affect controls that have a style defined lower in the hierarchy. Basically, the lower ones mask the higher ones, unless you used BasedOn. Use it in this fashion:
BasedOn="{StaticResource {x:Type <your type here>}}"

WPF Style Trigger

I change the FontSize of Text in a Style trigger, this causes the Control containing the text to resize as well. How can I change the Fontsize without affecting the parent's size?
A nice trick to isolate an element from its parent layout wise is to place the element in a Canvas
In the markup below there are two copies of your element
The first is hidden and establishes the size of your control
The second is visible but wrapped in a Canvas so its layout size does not affect the parent.
<Parent>
<Grid>
<Element Visibility="Hidden"/>
<Canvas>
<Element />
</Canvas>
<Grid>
</Parent>
You can increase the Padding at the same time you decrease the FontSize - this will cause the calculated height of the Button to remain the same:
<StackPanel>
<Button Content="ABC">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="FontSize" Value="20"/>
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="FontSize" Value="12"/>
<Setter Property="Padding" Value="5"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
<Button Margin="0,20" Content="123" FontSize="20"/>
<Button Content="Do Re Mi" FontSize="20"/>
</StackPanel>
You can do the reverse and set a negative Padding if the FontSize is increasing, as well.
You could also use a binding from FontSize to Padding to accomplish the same thing in a general way, but if you're only dealing with a fixed set of FontSizes it would be easier to just hardcode it as above.
There is absolutely NO need for hard-coded widths, crazy measure overrides, tricky bindings, or anything of that sort.
The solution is actually incredibly simple. Instead of changing the font size in a style trigger, create a simple control template for your button with a RenderTransform applied to the content presenter element. Add a ScaleTransform to the RenderTransform. Inside a IsPressed trigger definition set the vertical and horizontal scales on the ScaleTransform to a smaller ratio, say 0.8.
Using a RenderTransform will keep the layout of the pressed button the same with, so it won't influence the position of the other elements. By contrast, using a LayoutTransform would have actually caused the button container to shrink and the parent container's ArrangeOverride method would cause the adjacent buttons to move to fill the extra space.
I'm really busy right now so I'll leave the actual implementation up to you! ;-)
http://msdn.microsoft.com/en-us/library/system.windows.media.scaletransform.aspx
I am creating a ControlTemplate for a ButtonControl so it looks like a label (flat text, no borders) with triggers for IsKeyboardFocused, IsPressed, IsDefaulted etc.
The IsPressed is defined to drop the FontSize (from default of 30) down to 28. To give a pressed animation effect.
One use of these Buttons is a horizontal StackPanel of Button, separated by vertical separators. When the IsPressed trigger is fired on a button and it is resized, the entire row of buttons gets re adjusted, which is not a pleasing visual effect.
My preference is for a template based solution, to avoid introducing new controls in order to provide overrides. The only problem with the hard coded size approach is internationalisation, other languages will increase the orginal size.
The solution I am going with is to set the minWidth in C# after the button's DesiredSize has been calculated. Note that Width is NaN even after the Button is rendered hence the use/existence of DesiredSize. Later I will try and XAMLize the C#.
What kind of control are you using? If this is a HeaderedControl like a GroupBox or TabItem then you need to specifically set the HeaderTemplate like this:
<DataTemplate x:Key="MyHeaderTemplate">
<TextBlock Text="{Binding}" Fontsize="14" FontWeight="Bold" />
</DataTemplate>
I can think of a couple of things you could try:
You can override the Measure Pass of the control - when a control is rendered in WPF it undergoes two passes. The first is a 'measure pass', where the control comes up with what sizes that it wants to be. The second is the 'arrange pass', where it actually lays out the control. WPF provides a method called MeasureOverride. If you override this method you can provide custom behavior that can be used to adjust the size of the control.
Note - I believe that you will have to call the Measure method all of your controls children during this override in order to get your control to lay out properly.
Hard code the height and width on the control - this will override the control's DesiredSize with your values. While generally a not the greatest of ideas, it will work.

Resources