I have created a custom control called "Field", that inherits from ContentControl
and that contains a Grid
and a label
to expose the field label, and a ContentPresenter
to allow to put a control depending on the data we want to edit.
Then I created a custom control called "TextField", that inherits from Field
, that should put a TextBox
into the Content.
Here are the styles in Generic.xaml :
<Style TargetType="{x:Type controls:Field}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:Field}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid x:Name="grd" Margin="3px">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding Path=LabelLength, RelativeSource={RelativeSource AncestorType=Control}}" />
<ColumnDefinition Width="{Binding Path=ContentLength, RelativeSource={RelativeSource AncestorType=Control}}" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding Path=Label, RelativeSource={RelativeSource AncestorType=Control}}" />
<ContentPresenter Grid.Column="1" Content="{TemplateBinding Content}" Margin="{TemplateBinding Padding}" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type controls:FieldText}" BasedOn="{StaticResource {x:Type controls:Field}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:FieldText}">
<TextBox Grid.Column="1" MaxLines="1" TextWrapping="NoWrap" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
By evidence, this shows only a textbox when using a TextField
. But how could I just style the content (eg the TextBox in this example) by keeping the rest of the control inheriting the parent style?
I know I could rewrite the whole control for each derivated control, but that's against the inheritence principles, no? Would mean duplicated code (duplicated markup here) and if I change anything in the parent "Field" I would have to change it in every child control, with the risk of errors...