Форум программистов, компьютерный форум, киберфорум
C# .NET
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
96 / 96 / 16
Регистрация: 28.01.2008
Сообщений: 426
1

BrowsableAttribute для обытий класса, как скрыть от PropertyGrid некоторые Event

22.05.2012, 21:14. Показов 1633. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
здравствуйте, собственно интересует вопрос как скрыть от PropertyGrid некоторые Event, свойства я скрываю так, создав наследника от TypeConverter и установив его в атрибуты класса
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class PropertyShowTypeConverter : TypeConverter
    {
        public override bool GetPropertiesSupported( ITypeDescriptorContext context ) { return true; }
 
        public override PropertyDescriptorCollection GetProperties( ITypeDescriptorContext context, object value, Attribute[] attributes )
        {
            object[] ca = context.Instance.GetType().GetCustomAttributes( false );
            PropertyShowAttribute attr = ca.OfType<PropertyShowAttribute>().FirstOrDefault();
            
            PropertyDescriptorCollection coll = TypeDescriptor.GetProperties( value.GetType() );
            List<PropertyDescriptor> uotputCollection = new List<PropertyDescriptor>();
            
            foreach (PropertyDescriptor property in coll)
            {
                List<Attribute> attributeList = new List<Attribute>();
                foreach (Attribute attribute in property.Attributes)
                    if (attribute.GetType() != typeof(BrowsableAttribute))
                        attributeList.Add( attribute );
 
                if (attr != null)
                {
                    if (attr.properties.Contains(property.Name))
                        attributeList.Add( BrowsableAttribute.Yes );
                    else
                        attributeList.Add( BrowsableAttribute.No );
                }
                Attribute[] attributeArray = attributeList.ToArray();
                AttributeCollection newCollection = AttributeCollection.FromExisting( property.Attributes, attributeArray );
                if (newCollection.Contains( attributes ))
                    uotputCollection.Add( new CustomPropertyDescriptor( property, attributeArray ) );
            }
            return new PropertyDescriptorCollection( uotputCollection.ToArray(),
                (coll as System.Collections.IList).IsReadOnly );
        }
 
        protected sealed class CustomPropertyDescriptor : SimplePropertyDescriptor
        {
            private readonly PropertyDescriptor property;
 
            public CustomPropertyDescriptor( PropertyDescriptor property,
                Attribute[] attributes )
                : base( property.ComponentType, property.Name, property.PropertyType, attributes )
            {
                this.property = property;
            }
 
            private PropertyDescriptor PropertyDescriptor
            {
                get { return property; }
            }
 
            public override object GetValue( object component )
            {
                try
                {
                    return PropertyDescriptor.GetValue( component );
                }
                catch { }
                return null;
            }
 
            public override void SetValue( object component, object value )
            {
                if (value == null)
                    throw new Exception( "Value cannot be 'null'" );
                PropertyDescriptor.SetValue( component, value );
            }
        }
    }
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[AttributeUsage( AttributeTargets.Class, Inherited = true )]
    public class PropertyShowAttribute : Attribute
    {
        public readonly List<string> properties = new List<string>() 
        {
            "BackColor",
            "Cursor",
            "Dock",
        };
 
        public PropertyShowAttribute( bool clearStandard, params string[] args )
        {
            if (clearStandard)
                properties.Clear();
            foreach (string item in args)
                if (!properties.Contains( item ))
                    properties.Add( item );
        }
    }
C#
1
2
3
4
5
6
[TypeConverter( typeof( PropertyShowTypeConverter ) )]
    [PropertyShow( false, "LogicExpressionKeeper", "ParentTagIdent", "Name" )]
    public class AMButton : Button
    {
        //.............
    }
Добавлено через 3 часа 13 минут
вопрос решен, как всегда сам себе помог (см. класс ControlDesigner и ComponentDesigner)
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
22.05.2012, 21:14
Ответы с готовыми решениями:

Как создать событие event которое можно изменить для конкретного экземпляра класса?
создал свой класс MyDGV и создал в нем событие BeforeLoad и AfterLoad например Friend Event...

Как скрыть некоторые компоненты!
Напишите программу, которая отображала бы на первом этапе информацию о набираемом пароле, а на...

Как скрыть некоторые материалы в категории?
Есть вот такая страничка: ССЫЛКА Необходимо сделать так, чтобы пункты &quot;Материал тест 1&quot; и...

Как в производном классе скрыть некоторые свойства и методы базового?
Есть класс, производный от некого базового класса. Как в моем классе скрыть некоторые свойства и...

0
22.05.2012, 21:14
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
22.05.2012, 21:14
Помогаю со студенческими работами здесь

Несколько подчиненных отчетов - как можно некоторые скрыть/показать
Привет! Тут придумал себе головную боль: На главном отчете расположено несколько подчиненных...

Как упростить PropertyGrid для Chart?
В программе необходимо реализовать построение графиков. Использую компонент Chart. Для настройки...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru