Добрый день. Такая проблема. Свойство Modifiers в PropertyGrig отображает пять значений: Assembly, FamilyAndAssembly, Family, FamilyOrAssembly, Private и Public. Мне же тнеоюходимо чтобы оно имело следующие значения: Private, Public, Protected и Internal.
Кто подскажет решение?
Здравствуйте, minchenkov, Вы писали:
M>Добрый день. Такая проблема. Свойство Modifiers в PropertyGrig отображает пять значений: Assembly, FamilyAndAssembly, Family, FamilyOrAssembly, Private и Public. Мне же тнеоюходимо чтобы оно имело следующие значения: Private, Public, Protected и Internal.
M>Кто подскажет решение?
Заменить
PropertyDescriptor, отвечающий за свойство Modifiers на свой и переопределиь в нём свойство Converter. В этом самом Converter-е переопределить метод
GetStandardValues().
Здравствуйте, _FRED_, Вы писали:
_FR>Заменить PropertyDescriptor, отвечающий за свойство Modifiers на свой и переопределиь в нём свойство Converter. В этом самом Converter-е переопределить метод GetStandardValues().
Что то не получается. Ниже я показал, что сделал. Начну с самого начала.
В TreeView у меня выбирается элемент, а в PropertyGrid отображается свойства метаданного.
private void formDesignerView_SelectedItemChange(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
propgridElementProperties.SelectedObject = new RanetPropertyWrapper(nodeData.MetaData);
}
RanetPropertyWrapper предназначен для отображения русских имен в PropertyGrid.
/// <summary>
/// Класс для отображения только определенных свойств в PropertyGrid.
/// </summary>
public class RanetPropertyWrapper : ICustomTypeDescriptor
{
// Оборачиваемый объект
private object m_obj;
// Коллекция хранящая обертки над описаниями свойств.
private PropertyDescriptorCollection m_propsCollection;
/// <summary>
/// Позволяет получить обернутый объект.
/// </summary>
public object Unwrap
{
get
{
return m_obj;
}
}
/// <summary>
/// Конструктор.
/// </summary>
public RanetPropertyWrapper(object obj)
{
// Запоминаю оборачиваемый объект.
m_obj = obj;
// Создаем новую (пустую) коллекцию описаний свойств,
// в которую поместим обертки над реальными описаниями.
m_propsCollection = new PropertyDescriptorCollection(null);
// Создаю коллекцию, содержащую все свойства объекта
PropertyDescriptorCollection pdcAll =
TypeDescriptor.GetProperties(obj, true);
// Перебираем описания свойств, создаем для каждого
// из них обертку и помещаем ее в коллекцию.
foreach (PropertyDescriptor pd in pdcAll)
{
if (pd.Name != "Modifiers")
m_propsCollection.Add(new RanetPropertyDescriptor(pd));
else
m_propsCollection.Add(new ModifiersPropertyDescriptor(pd));
}
}
#region ICustomTypeDescriptor Members
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(Unwrap, true);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(Unwrap, true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(Unwrap, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(Unwrap, true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(Unwrap, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(Unwrap, true);
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(Unwrap, editorBaseType, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(Unwrap, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(Unwrap,attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return m_propsCollection;
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
return m_propsCollection;
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
В классе ModifiersPropertyDescriptor перекрыл свойство Converter:
/// <summary>
/// Класс, возвращающий свойство Modifiers
/// </summary>
public class ModifiersPropertyDescriptor : PropertyDescriptor
{
// свойство, которое будет отображаться
PropertyDescriptor m_PropDesc;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="PropDesc"></param>
public ModifiersPropertyDescriptor(PropertyDescriptor PropDesc) : base(PropDesc)
{
m_PropDesc = PropDesc;
}
#region PropertyDescriptor Overrided Members
// перекрываю свойство Converter
public override TypeConverter Converter
{
get
{
return new ModifiersTypeConverter(m_PropDesc);
}
}
public override Type ComponentType
{
get
{
return m_PropDesc.ComponentType;
}
}
public override bool IsReadOnly
{
get
{
return false;
}
}
public override Type PropertyType
{
get
{
return m_PropDesc.PropertyType;
}
}
public override bool CanResetValue(object component)
{
return m_PropDesc.CanResetValue(((RanetPropertyWrapper)component).Unwrap);
}
public override object GetValue(object component)
{
return m_PropDesc.GetValue(((RanetPropertyWrapper)component).Unwrap);
}
public override void ResetValue(object component)
{
m_PropDesc.ResetValue(((RanetPropertyWrapper)component).Unwrap);
}
public override void SetValue(object component, object value)
{
m_PropDesc.SetValue(((RanetPropertyWrapper)component).Unwrap, value);
}
public override bool ShouldSerializeValue(object component)
{
return m_PropDesc.ShouldSerializeValue(
((RanetPropertyWrapper)component).Unwrap);
}
#endregion
}
В классе ModifiersTypeConverter перекрыл метод GetStandardValues:
/// <summary>
/// Класс, отвечающий за отображение модификаторов доступа
/// </summary>
public class ModifiersTypeConverter : TypeConverter
{
private PropertyDescriptor m_PropDesc;
/// <summary>
/// Конструктор
/// </summary>
public ModifiersTypeConverter(PropertyDescriptor PropDesc)
{
m_PropDesc = PropDesc;
}
/// <summary>
/// Метод, обязательный для перекрытия
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
/// <summary>
/// Возвращает стандартные свойства
/// </summary>
/// <returns></returns>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
ArrayList descriptors = new ArrayList();
//descriptors.Add("tratata");
descriptors.Add(MemberAttributes.Final);
return new StandardValuesCollection(descriptors);
}
}
В итоге в PropertyGrid-е отображается единственное значение
Private.
Причем, если в свойстве ModifiersPropertyDescriptor.Converter возвратить null,
то в качестве значений свойства Modifiers будут отображены все элементы MemberAttributes.
Что я не доделал?
Здравствуйте, minchenkov, Вы писали:
_FR>>Заменить PropertyDescriptor, отвечающий за свойство Modifiers на свой и переопределиь в нём свойство Converter. В этом самом Converter-е переопределить метод GetStandardValues().
M>Что то не получается. Ниже я показал, что сделал.
Во-первых, перегрузи TypeDescriptor.
GetStandardValuesSupported(…)
Во-вторых

, таких свойств, как
M> // перекрываю свойство Converter
M> public override TypeConverter Converter
M> {
M> get
M> {
M> return new ModifiersTypeConverter(m_PropDesc);
M> }
M> }
быть не должно: добавь readonly-поле типа TypeConverter к классу и инициализируй его в конструкторе и возвращай из свойства.
Здравствуйте, _FRED_, Вы писали:
_FR>Во-первых, перегрузи TypeDescriptor.GetStandardValuesSupported(…)
_FR>Во-вторых
, таких свойств, как
_FR>M>> // перекрываю свойство Converter
M>> public override TypeConverter Converter
M>> {
M>> get
M>> {
M>> return new ModifiersTypeConverter(m_PropDesc);
M>> }
M>> }
_FR>
_FR>быть не должно: добавь readonly-поле типа TypeConverter к классу и инициализируй его в конструкторе и возвращай из свойства.
Доброе утро, что то опять не выкидывается список модификаторво доступа. Только одно значение, а не список.
Что я сделал:
1)Перекрыл метод TypeDescriptor.
GetStandardValuesSupported(…):
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
2) Объявил поле readonly, инициализировал в конструкторе и возвратил:
/// <summary>
/// Класс, возвращающий свойство Modifiers
/// </summary>
public class ModifiersPropertyDescriptor : PropertyDescriptor
{
// свойство, которое будет отображаться
PropertyDescriptor m_PropDesc;
readonly ModifiersTypeConverter mtc;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="PropDesc"></param>
public ModifiersPropertyDescriptor(PropertyDescriptor PropDesc) : base(PropDesc)
{
m_PropDesc = PropDesc;
mtc = new ModifiersTypeConverter();
}
#region PropertyDescriptor Overrided Members
// перекрываю свойство Converter
public override TypeConverter Converter
{
get
{
return mtc;
//return new ModifiersTypeConverter(m_PropDesc);
}
}
....
}
Всем спавибо за помощь. Я все сделал.
_Fred_, воспользовался твоим советом.