In HTML/CSS you can define a style which can be applied to many types of elements, e.g.:
.highlight { color:red; }
can be applied to both P and DIV, e.g.:
<p class="highlight">this will be highlighted</p> <div class="highlight">this will also be highlighted</div>
but in XAML you seem to have to define the TargetType for styles, otherwise you get an error:
<Style x:Key="formRowLabel" TargetType="TextBlock">
is there a way to allow a XAML style to be applied to multiple elements or even to leave it open as in CSS?
The setters in WPF styles are checked during compile time; CSS styles are applied dynamically.
You have to specify a type so that WPF can resolve the properties in the setters to the dependency properties of that type.
You can set the target type to base classes that contain the properties you want and then apply that style to derived classes. For example, you could create a style for Control objects and then apply it to multiple types of controls (Button, TextBox, CheckBox, etc)
<Style x:Key="Highlight" TargetType="{x:Type Control}"> <Setter Property="Foreground" Value="Red"/> </Style>
...
<Button Style="{StaticResource Highlight}" Content="Test"/> <TextBox Style="{StaticResource Highlight}" Text="Test"/> <CheckBox Style="{StaticResource Highlight}" Content="Test"/>
<!-- Header text style --> <Style x:Key="headerTextStyle"> <Setter Property="Label.VerticalAlignment" Value="Center"></Setter> <Setter Property="Label.FontFamily" Value="Trebuchet MS"></Setter> <Setter Property="Label.FontWeight" Value="Bold"></Setter> <Setter Property="Label.FontSize" Value="18"></Setter> <Setter Property="Label.Foreground" Value="#0066cc"></Setter> </Style> <!-- Label style --> <Style x:Key="labelStyle" TargetType="{x:Type Label}"> <Setter Property="VerticalAlignment" Value="Top" /> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="FontWeight" Value="Bold" /> <Setter Property="Margin" Value="0,0,0,5" /> </Style>
I think both of these methods of declaring a style might answer your question. In the first one, there is no TargetType specified, but the property names are prefixed with 'Label'. In the second one, the style is created for Label objects.
Another method to do it is:
<UserControl.Resources> <Style x:Key="commonStyle" TargetType="Control"> <Setter Property="FontSize" Value="24"/> </Style> <Style BasedOn="{StaticResource commonStyle}" TargetType="ListBox"/> <Style BasedOn="{StaticResource commonStyle}" TargetType="ComboBox"/> </UserControl.Resources>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With