tags:

views:

674

answers:

2

I have a number of UserControl classes:

  • DataTypeWholeNumber
  • DataTypeLine
  • DataTypeDate
  • DateTypeDuration
  • etc.

They all inherit from a plain C# class which inherits from UserControl which has no XAML attached to it. I had to do it this way since I was getting errors saying that XAML could not be inherited.

The problem is that the XAML for each of these UserControls is basically the same, so I would like to find some way to at least emulate XAML inheritance so that I don't have to repeat this code for 20 different classes:

<dataTypes:BaseDataType x:Class="TestDependencyProperty827.DataTypes.DataTypeLine"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dataTypes="clr-namespace:TestDependencyProperty827.DataTypes">
    <StackPanel Margin="{Binding Margin}">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="{Binding LabelWidth}"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <StackPanel Grid.Column="0" Orientation="Horizontal">
                <TextBlock Text="{Binding Label}" FontSize="14"/>
                <TextBlock FontSize="14" Text=":"/>
            </StackPanel>
            <TextBox Grid.Column="1" FontSize="12" HorizontalAlignment="Left" 
                      Text="{Binding Text}" 
                      Width="{Binding Width}"/>
        </Grid>
    </StackPanel>
</dataTypes:BaseDataType>

Has anyone run into this problem and found a solution to it?

+1  A: 

Use a Style that applies to the base class:

<Style TargetType="BaseClass">
    <Setter Property="Control.Template">
        <Control.Value>          
            <StackPanel Margin="{Binding Margin}">
            <!-- Rest of code here -->
        </Control.Value>
</Style>

Also, I question the need for UserControls for every one of the base types - why can't you just reuse the same UserControl everywhere?

Paul Betts
The reason I want a class for each DataType is e.g. for more complex datatypes such as Customer or Contract where not just a TextBox is being displayed but a dropdown here, three text boxes, etc. plus triggers and animations, etc. for a specific data type that are not in the other data types.
Edward Tanguay
A: 

A XAML class can't inherit from a XAML class, but a normal class can inherit from a XAML class - so if the XAML for all of those is the same put that XAML in BaseDataType and crate all the derived types as normal non-WPF c# classes.

If you need to derive other XAML user controls from BaseDataType than this is not possible but you can use styles, data templates or control templates to share the XAML between diffrent controls.

Nir