如何从 xml 填充属性的描述属性

本文关键字:属性 描述 填充 xml | 更新日期: 2023-09-27 18:32:53

我想从将从xml文件初始化的字符串填充属性的DescriptionAttribute。该属性将在属性网格中使用。

最主要的是从xml文件中获取描述。如何将其放入一个常量字符串中,然后我可以将其用作属性的描述属性。

我已经尝试了一些事情都没有成功,所以任何帮助将不胜感激。

还是有另一个 WEY 将 XML 值分配给描述?也许是类型转换器?请给我指出正确的方向。

public class1
{
    string BaboonDescription = "";
    string TigerDescription = "";
    const string SnakeDescription = "A snake is bla bla bla";
    // method that extracts the descriptions from the xml file.
    public void PopulateFromXml(string xmlfile)
    {
        XDocument xDoc = XDocument.Load(xmlfile);
        var items = from i in xDoc.Descendants("item")
                    select i;
        foreach (var item in items)
        {
            switch (item.Attribute("name").Value)
            {
                case "Baboon":
                    BaboonDescription = item.Value; // Assigns BaboonDescription the description from xml.
                    break;
                case "Tiger": 
                    TigerDesscription = item.Value; // Assigns TigerDescription the description from xml.
                    break;
                default:
                    break;
            }
        }
    }
}
public class2 : class1
{
    [Description(BaboonDescription)] // problem here. Telling me that I need const string. But i have to get the strings from an xml.
    public string Baboon { get; set; }
    [Description("tiger is bla bla")] // this one works but I want the description from the xml.
    public string Tiger { get; set; }
    [Description(SnakeDescription)] // this also works but I want the description from the xml.
    public string Snake { get; set; }
}

如何从 xml 填充属性的描述属性

DescriptionAttribute 不能同时编译和动态。

查看我对这个 SO 问题的回答,它演示了如何构建动态类型描述符:优化 PropertyGrid 的类

使用 DynamicTypeDescriptor 类,可以使用所需的描述属性生成包装类。