How to reference a generic type in the DataType attribute of a HierarchicalDataTemplate?

前端 未结 3 1003
花落未央
花落未央 2020-12-05 05:48

I have a class of MyClass and want to set it as the DataType for a HierarchicalDataTemplate.

What is the syntax for this in XAML? (I kno

3条回答
  •  情歌与酒
    2020-12-05 06:28

    This is not supported in WPF 3.x out of the box (I think it may be in 4.0, but I'm not sure); but it's easy to set up with a markup extension.

    First, you need to create a markup extension class that takes the type parameter as a constructor argument:

    public class MyClassOf : MarkupExtension
    {
      private readonly Type _of;
    
      public MyClassOf(Type of)
      {
        _of = of;
      }
    
      public override object ProvideValue(IServiceProvider serviceProvider)
      {
        return typeof(MyClass<>).MakeGenericType(_of);
      }
    }
    

    Now you use this markup extension in place of the x:Type extension:

    
    

    Needless to say, this can be generalised to allow instantiation of arbitrary generic types; I haven't shown this because it adds a wee bit more complexity.

提交回复
热议问题