Search code examples
wpfwindowgenerics

WPF Generic Windows


I want to make a reusable WPF Window suitable for different types T. I have a designer and a codebehind file.

can I do something like this?

/*  Code behind file */
public partial class MyWindows<T> : Window
{}

Solution

  • Unfortunately, what you want isn't quite possible.

    Update: Before .NET 4.0 (i.e. when this answer was originally written), XAML support for consuming generic types was very limited; e.g. generics only worked on the root element. In .NET 4.0, some restrictions were lifted.

    In .NET 4.0, you can construct a fully specialized generic type. So while XAML itself still has no concept of generic types, it can refer to specializations of generic types. (By analogy, XAML can't express the notion List<> but it can express the notion List<int>). For full details, see the MSDN page "Generics in XAML".

    You can construct instances of specialized generic types with the x:TypeArguments Directive. For example, with x bound to XAML's namespace, sys to the System namespace, and scg to System.Collections.Generic, and your own MyWindows' namespace bound to my then:

    • <my:MyWindows x:TypeArguments="x:String"> would construct a MyWindows<string> instance.
    • <scg:List x:TypeArguments="sys:Tuple(sys:String,sys:Int32)"> would construct a List<Tuple<string,int>>

    Using generic types is therefore no longer a problem in XAML!

    Alas, you want to define a generic type in XAML. That's not possible. There are two workarounds here. Firstly (and based on your comments on another question I think this is what you want) you can simple pass a type as a plain parameter. If you do this, you lose all the compile-time safety features that generics provide, but often enough those aren't relevant. Secondly, you can define a normal non-generic class with codebehind in XAML, and simply use a generic base class for code reuse. That way you get at least some proper generics safety and reuse.