Как внедрить собственный UITypeEditor для всех свойств типа с закрытым исходным кодом?
-
21-08-2019 - |
Вопрос
Я хочу избежать размещения EditorAttribute в каждом экземпляре определенного типа, для которого я написал собственный UITypeEditor.
Я не могу поместить EditorAttribute в тип, поскольку не могу изменить источник.
У меня есть ссылка на единственный экземпляр PropertyGrid, который будет использоваться.
Могу ли я указать экземпляру PropertyGrid (или всем экземплярам) использовать собственный UITypeEditor всякий раз, когда он встречает определенный тип?
Здесь — это статья MSDN, в которой представлена отправная точка того, как это сделать в .NET 2.0 или более поздней версии.
Решение
Обычно вы можете связать редакторов и т. д. во время выполнения через TypeDescriptor.AddAttributes
.Например ( Bar
свойство должно отображаться с символом «...», который отображает «Редактирование!»):
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
class Foo
{
public Foo() { Bar = new Bar(); }
public Bar Bar { get; set; }
}
class Bar
{
public string Value { get; set; }
}
class BarEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
MessageBox.Show("Editing!");
return base.EditValue(context, provider, value);
}
}
static class Program
{
[STAThread]
static void Main()
{
TypeDescriptor.AddAttributes(typeof(Bar),
new EditorAttribute(typeof(BarEditor), typeof(UITypeEditor)));
Application.EnableVisualStyles();
Application.Run(new Form { Controls = { new PropertyGrid { SelectedObject = new Foo() } } });
}
}
Другие советы
Решение Марка прямо применяет EditorAttribute к типу Bar глобально.Если у вас деликатный характер, вы можете предпочесть аннотировать свойства конкретных экземпляров.Увы, это невозможно с TypeDescriptor.AddAttributes
Мое решение состояло в том, чтобы написать обертку ViewModel<T>
, который копирует свойства из T, добавляя к некоторым из них дополнительные атрибуты.Предположим, у нас есть переменная datum
типа Отчет, мы бы использовали его так
var pretty = ViewModel<Report>.DressUp(datum);
pretty.PropertyAttributeReplacements[typeof(Smiley)] = new List<Attribute>() { new EditorAttribute(typeof(SmileyEditor),typeof(UITypeEditor))};
propertyGrid1.SelectedObject = pretty;
Где ViewModel<T>
определено:
public class ViewModel<T> : CustomTypeDescriptor
{
private T _instance;
private ICustomTypeDescriptor _originalDescriptor;
public ViewModel(T instance, ICustomTypeDescriptor originalDescriptor) : base(originalDescriptor)
{
_instance = instance;
_originalDescriptor = originalDescriptor;
PropertyAttributeReplacements = new Dictionary<Type,IList<Attribute>>();
}
public static ViewModel<T> DressUp(T instance)
{
return new ViewModel<T>(instance, TypeDescriptor.GetProvider(instance).GetTypeDescriptor(instance));
}
/// <summary>
/// Most useful for changing EditorAttribute and TypeConvertorAttribute
/// </summary>
public IDictionary<Type,IList<Attribute>> PropertyAttributeReplacements {get; set; }
public override PropertyDescriptorCollection GetProperties (Attribute[] attributes)
{
var properties = base.GetProperties(attributes).Cast<PropertyDescriptor>();
var bettered = properties.Select(pd =>
{
if (PropertyAttributeReplacements.ContainsKey(pd.PropertyType))
{
return TypeDescriptor.CreateProperty(typeof(T), pd, PropertyAttributeReplacements[pd.PropertyType].ToArray());
}
else
{
return pd;
}
});
return new PropertyDescriptorCollection(bettered.ToArray());
}
public override PropertyDescriptorCollection GetProperties()
{
return GetProperties(null);
}
}
Как определено выше, это заменяет свойства определенного типа, но вы можете заменить свойства по имени, если вам нужно большее разрешение.
Просто добавьте Атрибут редактора в свой класс.