When building Custom Controls there's a clear separation between the abstract model (class
) and its representation (Generic.xaml
). As always we should keep the view as dumb as possible, but likewise it pays to keep the implementation in the representation layer (and not clutter the model).
The only reason I can think of for overriding the default value in the class, would be when the order of initialization matters. For example, in case the inherited default value would throw an exception during the initialization of your class (before the Generic
style would be able to "override" it).
Generic XAML: the preferred method, this offers most flexibility. Provides a clear picture of the default implementation (see edit).
Method override: As mentioned, when the order of initialization matters. Leads to less clean code.
DefaultInitializer: Is used to provide default values for VS designer.
The DefaultInitializer extension is invoked when the user adds an object from the Toolbox to the design surface.
Derive from the DefaultInitializer class to configure default initial values for your object.
EDIT - Subclassing Custom Controls
This is another area where separation of concerns pays off, giving you a clear overview.
<Style TargetType="{x:Type local:MyButtonBase}">
<Setter Property="FontSize" Value="12"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
<Style BasedOn="{StaticResource {x:Type local:MyButtonBase}}"
TargetType="{x:Type local:MyButton}">
<!--Override inherited default value-->
<Setter Property="FontSize" Value="18"/>
<!--Add default values-->
<Setter Property="IsDefault" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyButton}">
...
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>