代码之家  ›  专栏  ›  技术社区  ›  Eric Smith

PropertyGrid-动态更改ReadOnlyAttribute

  •  1
  • Eric Smith  · 技术社区  · 15 年前

    唉,又是一个房地产泡沫问题。我想我可以绕过这个问题,直到我遇到了一个无法避免的问题。

    我能想到的唯一解决方案是为该属性可写的项创建单独的、几乎相同的类,为只读的项创建一个类,但这对我来说似乎有点不公平。

    帮助?:)

    3 回复  |  直到 15 年前
        1
  •  3
  •   Daniel Brückner    15 年前

    通过实现,可以向属性网格提供有关类属性的动态信息 ICustomTypeDescriptor .

    属性网格将调用 ICustomTypeDescriptor.GetProperties() 然后返回从中派生的对象的集合 PropertyDescriptors . 在您的实现中,您可以覆盖 PropertyDescriptor.IsReadOnly 属性并实现您的逻辑。

        2
  •  2
  •   Tom Anderson    15 年前

    我要做的是创建一个具有受保护版本属性的基类,然后创建两个继承基类的类,这些基类具有只读位和非只读位。

        3
  •  0
  •   Andy West    15 年前

    您可以尝试以下方法来避免涉及多个类的类型转换:

    class TestClass
    {
        private bool isMyPropertyReadOnly;
    
        public bool IsMyPropertyReadOnly
        {
            get { return isMyPropertyReadOnly; }
            set { isMyPropertyReadOnly = value; }
        }
    
        private int myVar;
    
        public int MyProperty
        {
            get { return myVar; }
    
            set
            {
                if (isMyPropertyReadOnly)
                {
                    throw new System.Exception("The MyProperty property is read-only.");
                }
                else
                {
                    myVar = value;
                }
            }
        }
    }
    
    推荐文章