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

后端 未结 8 1422
深忆病人
深忆病人 2020-12-18 18:19

I have a ViewModel defined like this:

public class LocationTreeViewModel : 
    ObservableCollection, INotifyPropertyChanged
               


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-18 18:58

    I know, that I'm a little late to the party, but I want post an answer for all those who may see this question in the future:

    It is possible.

    You can see the whole code in the answer to this question: DataTemplates and Generics. But since it is quite long, I will just copy the important bits. If you want more details, then look into the referenced question.

    1. You need to write a MarkupExtension which can provide a closed generic type.

      public class GenericType : MarkupExtension
      {
          public GenericType() { }
      
          public GenericType(Type baseType, params Type[] innerTypes)
          {
              BaseType = baseType;
              InnerTypes = innerTypes;
          }
      
          public Type BaseType { get; set; }
      
          public Type[] InnerTypes { get; set; }
      
          public override object ProvideValue(IServiceProvider serviceProvider)
          {
              Type result = BaseType.MakeGenericType(InnerTypes);
              return result;
          }
      }
      
    2. Now you can define your type which closes your generic type in xaml, and then use the closed generic type as DataType of an DataTemplate.

      
          
              
              
          
      
          
      
          
              
          
      
      
    3. Be happy that the defined DataTemplate gets automatically selected by WPF.

提交回复
热议问题