UWP - Subclassing built-in controls and inheriting styling behaviors - c#

Is it possible to subclass a control (AppBarToggleButton in my case) and "inherit" TargetType of the base class? What I want to achieve is to have a slightly customized AppBarToggleButton (with disabled auto-toggle behavior) put into CommandBar and make it look exactly as if it was regular AppBarToggleButton (i.e. receive style whatever is defined for AppBarToggleButton inside given command bar control template). They say, DefaultStyleKey should help, but it is inherited fine, but, alas, doesn't seem to participate in local style resolution/lookup.

I may need to subclass other controls for various purposes, so the ultimate goal here is to understand how local style resolution works internally and does target instance has any involvement in it or is it a completely external process.
In general, we need make Templated Control for custom AppBarToggleButton. When we make Templated Control with Visual Studio, it will generate Generic.xaml file in the Themes folder that used to declare the custom control's style. And the the custom control cs file like the following.
public sealed class CustomAppBarToggleButton : AppBarToggleButton
{
public CustomAppBarToggleButton()
{
this.DefaultStyleKey = typeof(CustomAppBarToggleButton);
}
}
If you don't want to edit the default style you could remove DefaultStyleKey line that used to binding current control with the style in the Generic.xaml file.
Open Generic.xaml file you will find the following. And it's empty style. If we want to do some small changes, you need copy the complete AppBarToggleButton style to replace it and edit the TargetType to local:CustomAppBarToggleButton. Then you can edit the style base on your requirement.
<Style TargetType="local:CustomAppBarToggleButton" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomAppBarToggleButton">
<Border
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And if your want to make a new dependency property, please define it in the cs file then use TemplateBinding to bind the property in the style. For more please check this document.

For anyone still stumbling upon this. I managed to solve a similar issue, inheriting from Button, using the approach described here https://stackoverflow.com/a/71338869/10468107
Specifically, adding
<Style BasedOn="{StaticResource DefaultButtonStyle}" TargetType="local:MyButton" />
solved it for me. So maybe it works for other types as well, using {StaticResource Default<TYPE>Style}

I have a similar need and am wondering if the answer is still the same. I have extended the basic ComboBox control to meet some behavioral requirements.
class ExtendedComboBox : ComboBox
I want the ExtendedComboBox instances to inherit the latest platform styling but they are instead getting styled differently. The first of these is an ExtendedComboBox (square corners, larger glyph), while the second is a generic ComboBox (rounded corners, smaller glyph).
The requirement is to have the two combo boxes styled the same way. I am reluctant to create an explicit Style for ExtendedComboBox because then if the style for the generic ComboBox changes the ExtendedComboBox will no longer match. Is there some way to just inherit the standard style?

Related

WPF hide slider track

I'm using WPF (and the MVVM framework) to create an interface which has a slider on it.
<Slider Value="{Binding MotorDemandSpeed}" Maximum="3500" />
I'm trying to hide the track part on the slider so that you are left with just the 'thumb tack'. This is what the slider currently looks like (styles are controlled by a theme):
I've looked around at various methods, however I can't find a method that changes only a single slider.
Help is appreciated.
You need to set the Template property of this particular Slider instance to be able to override its ControlTemplate:
<Slider Value="{Binding MotorDemandSpeed}" Maximum="3500">
<Slider.Template>
<ControlTemplate TargetType="Slider">
<!-- define the custom template without a track here... -->
</ControlTemplate>
</Slider.Template>
</Slider>
In order to change the appearance of a control you will need to modify the control template. Each control is made up of many parts, and each part many objects. You can modify individual parts (such as the track) with the correct x:Key and TargetType.
This Question has an example of modifying a scrollbar control template, which is most likely similar to the template of this slider you have. The first step would be to identify the Xaml file in your theme which this slider uses and find the parts that define the trackbar, thumb, etc. From there you should be able to recreate the control to your liking, or just completely remove parts you do not need.
Are you using any third party controls that may have information on how to edit their themes? Perhaps try investigating Modifying Control Templates to get a better understanding of control templates.
Here is the MDSN page for the slider control template, you may find this useful.

WPF Template Binding with more than 1 content

So, I have this Window. On it, I'm creating a list of TextBlocks and TextBoxes in pairs. When you click on either, they will put a number in the corresponding TextBox, and set some values in the background. This all works well now.
I have the following XAML to create a custom Checkbox (as it has the behavior I'd like to use for this). My problem is that I want to bind different content into both the TextBlock and TextBox. For the TextBlock, I bound to the Content property, but I can't find a suitable option to satisfy the second binding. I considered placing it in the tag, but this didn't feel right, and in any case, I'm already binding an index value I require into there.
<Style x:Key="CustomCHK" TargetType="{x:Type CheckBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CheckBox}">
<DockPanel LastChildFill="True">
<TextBox DockPanel.Dock="Right" Width="50" Height="30" />
<TextBlock Text="{TemplateBinding Content}" TextWrapping="Wrap" />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Feels like there should a simple solution to this, but I'm just trying to decide what's best. Do I create a custom checkbox class and just add a couple properties?
As always, I appreciate any direction you can offer me.
Unfortunately, there is no straightforward way to do this. I can see just two (somewhat flawed) workarounds:
Subclass CheckBox to suit your needs, and add the additional content properties that you need. The advantage is that this will fully enable your IDE's programming help for setting the content properties, and those properties will be typesafe. The downside is that your will need to add C# code for the sole purpose of declaring the additional content properties (i.e. without adding any "behavioral logic"), which somehow seems to conflict with a "clean" XAML-only for presentation approach.
You could try passing an array to the Content property, and then place several ContentPresenter instances in your control template, each of which bind to another item in the array. Binding property paths should support indexed access, though your code may become a bit verbose, as arrays in XAML have to be written explicitly by using the x:Array markup extension.

customize Style CheckList RadTreeView

Is there a way to change the style of checkboxes when the ItemsOptionListType="CheckList"
inside a RadTreeView?
There are a couple of ways of doing this that I can think of, but sadly neither of them is particularly easy.
One way is to use Blend or a similar tool to obtain the template for the RadTreeViewItem class. The RadTreeViewItem class and its template are in the Telerik.Windows.Controls.Navigation assembly. Take a copy of this template and modify the CheckBox within this template to customise its appearance as you wish.
To use the template, add a ControlTemplate and a Style to the <UserControl.Resources> element of a XAML page, as follows:
<UserControl.Resources>
<ControlTemplate x:Key="myRadTreeViewItemTemplate" TargetType="telerik:RadTreeViewItem">
<!-- modified template goes here... -->
</ControlTemplate>
<Style TargetType="telerik:RadTreeViewItem">
<Setter Property="Template" Value={StaticResource myRadTreeViewItemTemplate}" />
</Style>
</UserControl.Resources>
This should then apply the modified template to any RadTreeViews in the same XAML file.
Note that we have to use an implicit style (i.e. one without an x:Key), since there seems to be no other way to tell a RadTreeView to apply a given style to its child items.
Alternatively, you can modify a built-in theme. This approach could also change the styles of CheckBoxes used within other Telerik controls in your application, for example in a GridViewCheckBoxColumn within a RadGridView.
EDIT: if you want the template for the CheckBox as used in the RadTreeView by default,
you'll find it in Themes\Office\Black\System.Windows.Controls.xaml within the Telerik.Windows.Controls assembly. This assumes you're using the 'Office Black' theme; adjust the path of this file if you're using a different Telerik theme.

Create template-less user control. OnApplyTemplate

I have "Service" custom control that doesn't need to be visual. I just add it to my view so it can bind to VM and perform some functionality.
Style looks like so:
<Style TargetType="controls:IdattInteractions">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="controls:IdattInteractions">
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
When view initialized I don't get OnApplyTemplate called on my control. Is that because ControlTemplate empty? How do I achieve functionality I need? I need to proble visual tree around this control for some functionality and I wanted to do it inside OnApplyTemplate.
How should I go about this?
As far as I know, if your "control" is not visual, then it should be a business logic object of some class, running in memory and interacting with the ViewModel if needed. No need to declare it in XAML.
I'm guessing you "add it to your view" by declaring as a resource. If that's the case, the reason you never receive a call to OnApplyTemplate is because your control is not part of the visual tree. (Test it out: in the debugger, break at the end of your constructor. You'll have a ResourceDictionary with your control living inside. Try to keep following the Parent property until you reach your control. You'll find the Parent will be null quite quickly within the hierarchy.)
To get a call from OnApplyTemplate, you'll need to add your custom control into the root layout container of some other control. Then you'll be inside the visual tree.

Difference between Style and ControlTemplate

Could you tell me what is the main differences between Style and ControlTemplate ?
When or why to use one or the other ?
To my eyes, they are exactly the very same. As I am beginner I think that I am wrong, thus my question.
In a style you set properties of a control.
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Red"/>
</Style>
<Button Style="{StaticResource MyButtonStyle}"/>
All buttons that use this style will have their Backgrounds set to Red.
In a template you define the UI (structure) of the control.
<ControlTemplate x:Key="MyButtonTemplate" TargetType="Button">
<Grid>
<Rectangle Fill="Green"/>
<ContentPresenter/>
</Grid>
</ControlTemplate>
<Button Template="{StaticResource MyButtonTemplate}"/>
All buttons that use this template will have a green background that cannot be changed.
Values set in a template can only be replaced by replacing the entire template. Values in a style can be replaced by setting the value explicitly when using the control. That is why is better to use the properties of the control by using TemplateBinding instead of coding values.
<ControlTemplate x:Key="MyButtonTemplate" TargetType="Button">
<Grid>
<Rectangle Fill="{TemplateBinding Background}"/>
<ContentPresenter/>
</Grid>
</ControlTemplate>
Now the template uses the value of the Background property of the button it is applied to, so it can be customized:
<Button Template="{StaticResource MyButtonTemplate}" Background="Yellow"/>
Another useful feature is that controls can pick up a default style without having a specific style being assigned to them. You can't do that with a template.
Just remove the x:Key attribute of the style (again: you can't do this with templates). All buttons in the visual tree below the style will have this style applied.
Combining Templates and Styles is extra powerful: you can set the Template property in the style:
<Style TargetType="Button">
<Setter Property="Background" Value="Red"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="{TemplateBinding Background}"/>
<ContentPresenter/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
No indeed you are quite wrong.
Styles set properties on controls. ControlTemplate is a property shared by most controls that specify how they are rendered.
To elaborate, you can use a style to group settings for a bunch of properties so you can re-use that to standardize your controls. Styles can be set explicitly on controls or applied too all of a certain type.
Control Templates can be set by a style or set explicitly on a control to change the way it appears. All controls have default templates (and styles for that matter) that are embedded in the .net wpf assemblies. It is quite enlightening to see these and understand how the wpf developers implemented the normal versions of all controls. If you have Expression blend installed, look in its "SystemThemes" folder.
UPDATE:
To understand how Styles and ControlTemplates can "add controls". In some way or another, the ControlTemplate is the only way to define the controls a control is made up of. But, some default .net controls allow you to use controls in place of text.
For example:
<GroupBox>
<GroupBox.Header>
<CheckBox/>
</GroupBox.Header>
</GroupBox>
This "adds" a checkbox to the groupbox without changing the ControlTemplate, but this is because the default ControlTemplate for GroupBox allows anything as the Header. This is done by using special controls such as ContentPresenter.
However, sometimes the default ControlTemplate for a control doesn't allow you to change something that you want to change via properties. Then you must change the ControlTemplate.
Whether you set the Properties of a control (Content, Header, ControlTemplate, IsEnabled, etc.) directly or via a style does not matter, Styles are only a convenience.
Hopefully this answers your question more clearly.
You can think of a Style as a convenient way to apply a set of property values to more than one element. You can change the default appearance by setting properties, such as FontSize and FontFamily, on each TextBlock element directly. However, if you want your TextBlock elements to share some properties, you can create a Style in the Resources section of your XAML file.
On the other hand, a ControlTemplate specifies the visual structure and visual behavior of a control. You can customize the appearance of a control by giving it a new ControlTemplate. When you create a ControlTemplate, you replace the appearance of an existing control without changing its functionality. For example, you can make the buttons in your application round instead of the default square shape, but the button will still raise the Click event.
Ref: http://msdn.microsoft.com/en-us/library/ms745683.aspx
I found some interesting differences in
The difference between styles and templates (msdn)
Style:
You can set only pre-existing properties in the style. For example, you cannot set a default value for a property that belongs to a new part that you added to the template.
Template:
When you modify a template, you have access to more parts of a control than when you modify a style. For example, you can change the way the pop-up list appears in a combo box, or you change the look of the button that triggers the pop-up list in the combo box by modifying the items template.
Style:
You can use styles to specify the default behavior of a control. For example, in a style for a button, you can specify a trigger so that when users move their mouse pointer over the button, the background color will change. These property changes are instantaneous (they cannot be animated gradually).
Template:
You can specify the behavior of any new and existing parts in a template by using triggers. For example, you can specify a trigger so that when users move their mouse pointer over a button, the color of one of the parts will change. These property changes can be instantaneous or animated gradually to produce a smooth transition.
OK, I had the exact same question and the answers I found in this thread pointed me in the right direction so I'm sharing, if only so I can understand it better myself.
A Style is more flexible than a ControlTemplate.
From Windows Presentation Foundation Unleashed, Adam Nathan and gang (writers) state this:
"Besides the convenience of combining a template [with a style using the Style's ControlTemplate setter] with arbitrary property settings, there are important advantages of doing this [setting the ControlTemplate setter on a style]:
It gives you the effect of default templates. For example, when a typed Style gets applied to elements by default, and that Style contains a custom control template, the control template gets applied without any explicitly markings on those elements.
It enables you to provide default yet overridable property valus that control the look of the template. In other words, it enables you to respect the templated parent's properties but still provide your own default values."
In other words, creating a style allows the user of the Style's Template setter to override the values set, even if they did not use a TemplateBinding ({TemplateBinding Width} for example). If you hardcoded the Width in your style, the user of the Style could still override it, but if you hardcoded that Width property in a Template, the user is stuck with it.
Also, (and this is kind of confusing) when using a ContentTemplate with a TemplateBinding the onus is on the user to set that property otherwise it will use the default property for the TargetType. If you use a style, you can override the default property of the TargetType by using a setter for the property and then applying a TemplateBinding referencing back to that setter. The book explains it better, page 338 (Mixing Templates with Styles)

Categories

Resources