简体   繁体   中英

what is the best way to emulate XAML code inheritance?

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?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM