Search code examples
c#wpfcontroltemplatemdi

Apply template to control and children


I've been tinkering around with WPF MDI, which sets the control template for MDI Child objects. So when you add an MdiChild object and set its Content to a UserControl it looks good, but if you inherit from MdiChild then it doesn't work.

The template code looks something like this:

<Style TargetType="{x:Type local:MdiChild}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MdiChild}">
<!-- ... -->

I'd like this template to apply not just to MdiChild, but also to anything that derives from it. How can I go about this? The only way I can think of is to create a style targeting each derived class that is based on the MdiChild style, but that's not very desirable.


Solution

  • You have to declare style for each derived type but with WPF you have power to inherit from base style using BasedOn.

    <Style TargetType="{x:Type local:DerivedMdiChild}"
           BasedOn="{StaticResource {x:Type local:MdiChild}}">
       ......
    </Style>
    

    This way all setters, triggers etc. will be inherited and you don't have to redefine them again for each derived style. Moreover, it gives you power to override setter of base style in case you want some different behaviour in derived version.