I have been studying Xamarin Forms lately and in the chapter on styles I found myself wondering if you can inherit default styles.
For example, you can specify a default style for all controls of a particular class. You can also explicitly use styles for ancestor classes - for example a label can reference a style that targets a control. I wondered if you could specify a default style for a class and have it affect all derived classes.
Here's the code that tests this question. I define a default style for "Control" and check to see if a "Label" control will inherit it. If it does, the label will have a red background.
<Window x:Class="InheritDefaultStyle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:InheritDefaultStyle"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<Style x:Key="InheritedStyle" TargetType="Control">
<Setter Property="Background" Value="Green"/>
</Style>
<Style TargetType="Control">
<Setter Property="Background" Value="Red"/>
</Style>
</ResourceDictionary>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Label Style="{StaticResource InheritedStyle}" Content="If the background is GREEN you can inherit a named style"/>
<Label Content="If the background is RED you can inherit a default style"></Label>
</StackPanel>
</Window>
The result of this test is...
As you can see, a default style only applies to the control type specified in the TargetType, but not to descendants. This means if I create a custom control that derives from Label it will not inherit the default style for Label. This is not what most developers would expect or want.
No comments:
Post a Comment