How to reflect class inheritance in WPF / XAML?

(First: I have programming experience, but I start with XAML / WPF / StackOverflow. So please forgive something "stupid" and ask if something is clear or if you need more information. Thanks. )

Introduction: I have a base class Itemwith some properties (eg Title, Notesetc.). From this, I have some derived classes such as ContactItem, MediaItemetc. With additional properties, which act as base classes for other specialized types of elements (e.g. ImageItem, MusicItemand VideoItemwhich are derived from MediaItem, Personand Institutionreceived from ContactItem).

In WPF, I need a page that can display several types of elements. I am currently using ItemsPanelthis for this and have begun to specify data patterns for each type of element - and there are many (over 50).

Problem: Now I want something like “inheritance” of control elements (for example, “base” UserControlc ContentPresenterand add additional controls for additional properties of derived classes / control templates).

What would be the best way to handle this in WPF / XAML without having to copy / paste controls from base classes for derived item types in data templates?

Any idea or hint in the right direction would be great. If you need any code or additional information, please let me know.

+4
source share
1 answer

You can simply insert each base class UserControlinside more derived UserControls, but you may find that this can soon become unmanageable. Another way would be to use an element ContentControlto display sections of a larger one DataTemplatefrom another DataTemplateas follows:

<DataTemplate x:Key="NameTemplate" DataType="{x:Type ViewModels:UserViewModel}">
    <TextBlock Text="{Binding Name}" />
</DataTemplate>
...
<DataTemplate DataType="{x:Type ViewModels:UserDerivedViewModel}">
    <ContentControl Content="{Binding}" 
        ContentTemplate="{StaticResource NameTemplate}" />
    <TextBlock Text="{Binding Age}" />
</DataTemplate>
+4
source

All Articles