4/29/2013

How can we reduce the repetitive style declaration in WPF?

Xaml is also needed refactoring. Especially for the style, there is a 'BasedOn' property.
It seems like enum or #define of  c++.

Let's look below xaml code,
   <Style TargetType="{x:Type Label}">
      <Setter Property="FontFamily" Value="Arial" />
      <Setter Property="FontSize" Value="10" />
      <Setter Property="HorizontalAlignment" Value="Right" />
      <Setter Property="FontWeight" Value="Bold" />
   </Style>

   <Style TargetType="{x:Type Button}">
      <Setter Property="FontFamily" Value="Arial" />
      <Setter Property="FontSize" Value="10" />
      <Setter Property="Margin" Value="4" />
   </Style>


In the above code, line 2, 3 and line 9, 10 are exactly the same. In case, by means of  'BasedOn' property, the duplicate can be removed.
  <Style x:Key="defaultControlStyle" 
          TargetType="{x:Type Control}">
      <Setter Property="FontFamily" Value="Arial" />
      <Setter Property="FontSize" Value="10" />
  </Style>
  
  <Style TargetType="{x:Type Label}"
           BasedOn="{StaticResource defaultControlStyle}">
      <Setter Property="HorizontalAlignment" Value="Left" />
      <Setter Property="FontWeight" Value="Bold" />
  </Style>
  <Style TargetType="{x:Type Button}"
           BasedOn="{StaticResource defaultControlStyle}">
      <Setter Property="Margin" Value="2" />
  </Style>
 
 To begin with, 'defaultControlStyle' is declared as a common style, and then each control style are using by 'BasedOn' property.
 
The use of repetitive code is a stairway to overwork in all IT fields.

No comments:

Post a Comment