.NET 4 RTM MetadataType attribute ignored when using Validator

痞子三分冷 提交于 2019-11-28 12:01:46
bart

It seems that the Validator doesn't respect MetadataTypeAttribute:

http://forums.silverlight.net/forums/p/149264/377212.aspx

The relationship must be explicity registered:

 TypeDescriptor.AddProviderTransparent(
      new AssociatedMetadataTypeTypeDescriptionProvider(
          typeof(Stuff),
          typeof(StuffMetadata)), 
      typeof(Stuff)); 

This helper class will register all the metadata relationships in an assembly:

public static class MetadataTypesRegister
{
    static bool installed = false;
    static object installedLock = new object();

    public static void InstallForThisAssembly()
    {
        if (installed)
        {
            return;
        }

        lock (installedLock)
        {
            if (installed)
            {
                return;
            }

            foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
            {
                foreach (MetadataTypeAttribute attrib in type.GetCustomAttributes(typeof(MetadataTypeAttribute), true))
                {
                    TypeDescriptor.AddProviderTransparent(
                        new AssociatedMetadataTypeTypeDescriptionProvider(type, attrib.MetadataClassType), type);
                }
            }

            installed = true;
        }
    }
}

Supplying an instance of the metadata class instead of the main class to the ValidationContext constructor seems to work for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!