Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you define multiple TargetTypes for one XAML style?

Tags:

styles

wpf

xaml

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?

like image 577
Edward Tanguay Avatar asked Apr 29 '09 14:04

Edward Tanguay


2 Answers

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"/> 
like image 149
Josh G Avatar answered Sep 30 '22 00:09

Josh G


<!-- 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> 
like image 24
Gaurang Avatar answered Sep 29 '22 22:09

Gaurang