2013-10-28 33 views
4

我有一个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; } 

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

编辑:

我试着下面的代码,但这个设置只读属性为对象的每个实例!我想按照每个对象来做。有时一个对象可能具有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 { } 
    } 
} 
+0

PropertyGrid'多少'你在你的应用程序中使用?如果一次只使用1个'PropertyGrid',我认为你的目的可以实现,我们仍然需要改变'Attribute'类型,但是在选择一个对象之前,我们将相应地切换'ReadOnly',并且应该这样做招。 –

回答

1

我能够使用此文章中的库完成我所需要的操作(只读属性的对象级别分配)。好的是,它使我仍然可以使用.NET PropertyGrid,并只使用自定义属性来处理动态设置。

+1

无法链接到CodeProject文章。 – Crackerjack

0

使用反射来获得ReadOnlyAttribute类的实例的引用,然后切换该实例上IsReadOnly属性。最后,如果需要将PropertyObjects的SelectedObjects设置为null,然后重置它,则重新选择PropertyGrid中的项目。您也许可以使用PropertyGrid RefreshTabs方法来做到这一点,我不确定。

编辑:

不幸的是,IsReadOnly属性本身是只读......在这种情况下,我们不得不使用反射来改变支持字段的值IsReadOnly属性。

0

添加只读

enter code here 
TextBoxID.Attributes.Add("readonly","true"); 

删除只读

enter code here 
TextBoxID.Attributes.Remove("readonly");