Common Windows WPF

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

Is it possible to do something like this?

/* Code behind file */ public partial class MyWindows<T> : Window {} 
+6
generics wpf window
source share
2 answers

Unfortunately, what you want is not entirely possible.

Update: Prior to .NET 4.0 (i.e. when this answer was originally written), XAML support for consuming generic types was very limited ; for example, generics worked only on the root element. In .NET 4.0, some restrictions have been removed.

In .NET 4.0, you can create a fully specialized generic type. Therefore, although XAML itself still does not have the concept of generic types, it can refer to specializations of generic types. (By analogy, XAML cannot express the concept of List<> , but it can express the concept of List<int> ). For more information, see the MSDN General in XAML page.

You can instantiate specialized generic types using x:TypeArguments Directive . For example, with x associated with the XAML namespace, sys into the System and scg to System.Collections.Generic , and your own MyWindows namespace is bound to my , and then:

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

Using generic types is therefore no longer an issue in XAML!

Alas, you want to define a generic type in XAML. It's impossible. There are two workarounds here. Firstly (and based on your comments on another matter, I think this is what you want), you can just pass the type as a simple parameter. If you do this, you will lose all the compile-time security features that generics provide, but often enough to not be relevant. Secondly, you can define a regular non-generic class with XAML code and just use a common base class to reuse the code. This way you get at least some proper generic safety and reuse.

+3
source share

Shamelessly copied from here (and therefore not verified)

 public class ViewBase<T> : Window, IView where T : class, IViewModel { public virtual T Model { get { return DataContext as T; } set { DataContext = value; } } } 

and xaml

 <src:ViewBase x:Class="View" x:TypeArguments="src:IViewModel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:src="clr-namespace:MyNamespace" Height="480" Width="640"> ... </src:ViewBase> 
+6
source share

All Articles