gpt4 book ai didi

c# - 将 ICustomTypeDescriptor.GetProperties 返回的属性动态更改为只读

转载 作者:行者123 更新时间:2023-11-30 12:18:17 24 4
gpt4 key购买 nike

我有一个实现 ICustomTypeDescriptor 的类,用户可以在 PropertyGrid 中查看和编辑它。我的类还有一个 IsReadOnly 属性,它确定用户以后是否能够保存他们的更改。如果用户无法保存,我不想让他们进行更改。因此,如果 IsReadOnly 为真,我想覆盖任何在属性网格中可编辑为只读的属性。

我正在尝试使用 ICustomTypeDescriptor 的 GetProperties 方法将 ReadOnlyAttribute 添加到每个 PropertyDescriptor。但它似乎没有用。这是我的代码。

 public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
List<PropertyDescriptor> fullList = new List<PropertyDescriptor>();

//gets the base properties (omits custom properties)
PropertyDescriptorCollection defaultProperties = TypeDescriptor.GetProperties(this, attributes, true);

foreach (PropertyDescriptor prop in defaultProperties)
{
if(!prop.IsReadOnly)
{
//adds a readonly attribute
Attribute[] readOnlyArray = new Attribute[1];
readOnlyArray[0] = new ReadOnlyAttribute(true);
TypeDescriptor.AddAttributes(prop,readOnlyArray);
}

fullList.Add(prop);
}

return new PropertyDescriptorCollection(fullList.ToArray());
}

这甚至是使用 TypeDescriptor.AddAttributes() 的正确方法吗?在调用后调试时,AddAttributes() 属性仍然具有相同数量的属性,其中没有一个是 ReadOnlyAttribute。

最佳答案

TypeDescriptor.AddAttributes类级别 属性添加到给定对象或对象类型,而不是属性级别 属性。最重要的是,我认为它除了对返回的 TypeDescriptionProvider 的行为有任何影响。

相反,我会像这样包装所有默认属性描述符:

public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return new PropertyDescriptorCollection(
TypeDescriptor.GetProperties(this, attributes, true)
.Select(x => new ReadOnlyWrapper(x))
.ToArray());
}

其中 ReadOnlyWrapper 是这样一个类:

public class ReadOnlyWrapper : PropertyDescriptor
{
private readonly PropertyDescriptor innerPropertyDescriptor;

public ReadOnlyWrapper(PropertyDescriptor inner)
{
this.innerPropertyDescriptor = inner;
}

public override bool IsReadOnly
{
get
{
return true;
}
}

// override all other abstract members here to pass through to the
// inner object, I only show it for one method here:

public override object GetValue(object component)
{
return this.innerPropertyDescriptor.GetValue(component);
}
}

关于c# - 将 ICustomTypeDescriptor.GetProperties 返回的属性动态更改为只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2414717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com