DataTemplate.DataType = Collection <Entity>?

Shi*_*mmy 8 wpf entity-framework generic-list datatemplate generic-programming

有没有办法创建一个处理项目列表的数据模板?

我有Contact.Phones(EntityCollection<Phone>),我希望数据模板处理列表 - 添加删除编辑等.

有没有办法将DataTemplate的DataType属性设置为泛型EntityCollection<Phone>

Ray*_*rns 7

在我的翡翠数据基础(EDF)工具中,我通过创建比x:Type更强大的MarkupExtension来解决这个问题,它也可以指定泛型类型.这样我就可以写:

 <DataTemplate TargetType="{edf:Type generic:ICollection{local:Entity}}" />
Run Code Online (Sandbox Code Playgroud)

这是我用过的东西:

  [MarkupExtensionReturnType(typeof(Type))]
  public class TypeExtension : MarkupExtension
  {
    public TypeExtension() { }
    public TypeExtension(string typeName) { TypeName = typeName; }
    public TypeExtension(Type type) { Type = type; }

    public string TypeName { get; set; }
    public Type Type { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
      if(Type==null)
      {
        IXamlTypeResolver typeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
        if(typeResolver==null) throw new InvalidOperationException("EDF Type markup extension used without XAML context");
        if(TypeName==null) throw new InvalidOperationException("EDF Type markup extension used without Type or TypeName");
        Type = ResolveGenericTypeName(TypeName, (name) =>
        {
          Type result = typeResolver.Resolve(name);
          if(result==null) throw new Exception("EDF Type markup extension could not resolve type " + name);
          return result;
        });
      }
      return Type;
    }

    public static Type ResolveGenericTypeName(string name, Func<string, Type> resolveSimpleName)
    {
      if(name.Contains('{'))
        name = name.Replace('{', '<').Replace('}', '>');  // Note:  For convenience working with XAML, we allow {} instead of <> for generic type parameters

      if(name.Contains('<'))
      {
        var match = _genericTypeRegex.Match(name);
        if(match.Success)
        {
          Type[] typeArgs = (
            from arg in match.Groups["typeArgs"].Value.SplitOutsideParenthesis(',')
            select ResolveGenericTypeName(arg, resolveSimpleName)
            ).ToArray();
          string genericTypeName = match.Groups["genericTypeName"].Value + "`" + typeArgs.Length;
          Type genericType = resolveSimpleName(genericTypeName);
          if(genericType!=null && !typeArgs.Contains(null))
            return genericType.MakeGenericType(typeArgs);
        }
      }
      return resolveSimpleName(name);
    }
    static Regex _genericTypeRegex = new Regex(@"^(?<genericTypeName>\w+)<(?<typeArgs>\w+(,\w+)*)>$");

  }
Run Code Online (Sandbox Code Playgroud)

泛型类型名称解析代码在一个单独的方法中,因为EDF中的某些其他代码也使用它.您可以将它们组合成一个方法.


T.J*_*aer 3

将您的通用列表包装在一个新类中,该类对您的通用列表进行子类化,而不添加任何内容。这使得从 XAML 绑定到列表成为可能。此处对此进行了描述: 我可以在 XAML 中指定泛型类型(.NET 4 Framework 之前的版本)吗?