Search code examples
c#wpffluentfluent-interface

Fluent WPF API for inherited properties


Occasionally I'll have some WPF C# code that I'd like to write in a "fluent" manner.

For example, I might want to setup a Window containing a ScrollViewer:

new Window()
    .SetContent(
        new ScrollViewer()
            .SetContent(
                ...))

To achieve this sort of API, I've been using extension methods such as these:

static class FluentScrollViewer
{
    public static ScrollViewer SetContent(this ScrollViewer obj, object val)
    { obj.Content = val; return obj; }
}

static class FluentWindow
{
    public static Window SetContent(this Window obj, object val)
    { obj.Content = val; return obj; }
}

Now, Window and ScrollViewer both inherit the Content property from ContentControl. Yet, I've had to define the SetContent extension methods for each class separately.

If I try to do something like this instead:

static class FluentContentControl
{
    public static ContentControl SetContent(this ContentControl obj, object val)
    { obj.Content = val; return obj; }
}

and then use it like so:

new Window().SetContent(...)

the SetContent method doesn't return a Window of course.

Is there way to define SetContent over ContentControl and have it do the "right thing" so as to avoid defining lots of individually speciallized methods which are similar except for the type?


Solution

  • You can use generics:

    public static TControl SetContent<TControl>(this TControl obj, object val)
    where TControl : ContentControl
    { 
        obj.Content = val; 
        return obj; 
    }