c# - 在 PropertyGrid 中动态设置属性的只读属性

标签 c# .net winforms readonly propertygrid

我有一个 PropertyGrid 用于显示辅助类中的属性。我将辅助类分配给 PropertyGrid,如下所示:

myPropertyGrid.SelectedObject = mySettingsHelper;

在帮助程序类中,我在设计时分配了 ReadOnlyAttribute,如下所示:

[DisplayName("DisplayExA"),
Description("DescriptionExA"),
ReadOnlyAttribute(true)]
public string PropertyA { get; set; }

[DisplayName("DisplayExB"),
Description("DescriptionExB"),
ReadOnlyAttribute(false)]
public string PropertyB { get; set; }

[DisplayName("DisplayExC"),
Description("DescriptionExC"),
ReadOnlyAttribute(true)]
public string PropertyC { get; set; }

但现在我需要能够在运行时动态更改各个属性的此属性。根据某些标准,其中一些属性可能需要是只读的或不是只读的。我将如何在运行时动态地进行更改?

编辑:

我尝试了以下代码,但这为对象的每个实例设置了 ReadOnly 属性!我想按对象做。有时一个对象的 PropertyA 可能是只读的,而第二个对象的 PropertyA 不是只读的。

public static class PropertyReadOnlyHelper
{
    public static  void SetReadOnly(object container, string name, bool value)
    {
        try
        {
            PropertyDescriptor descriptor = TypeDescriptor.GetProperties(container.GetType())[name];
            ReadOnlyAttribute attribute = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
            FieldInfo fieldToChange = attribute.GetType().GetField("isReadOnly",
                                                System.Reflection.BindingFlags.NonPublic |
                                                System.Reflection.BindingFlags.Instance);
            fieldToChange.SetValue(attribute, value);
        }
        catch { }
    }
}

最佳答案

我能够使用此 CodeProject 中的库完全满足我的需要(只读属性的对象级分配)文章。很棒的是,它使我能够继续使用 .NET PropertyGrid 并仅使用自定义属性来处理动态设置。

关于c# - 在 PropertyGrid 中动态设置属性的只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19640823/

相关文章:

c# - 是否有内置方法来访问项目的 csproj 文件数据?

.net - 使用 Entity Framework 批准对实时数据的更改

c# - 如何将不同面板中的单选按钮分组为一个组?

.net - 使用 mono 提高 .Net XML 序列化程序的性能

c# - TreeView 中不可选择的节点

c# - C# 中 Overlapped PictureBox 的透明度问题

c# - 为什么 NumberStyles.AllowThousands 在传递负数时会导致异常?

c# - ??有 2 个字符串的运算符?

c# - 什么时候应该尝试消除 switch 语句?

c# - 创建一个通用方法来接受类型对象并返回一个新的类型对象