最近接触C#的PropertyGrid比较多,得到了两个小心得记录一下。

第1点是关于控制PropertyGrid中属性的只读属性的。

我遇到的问题是这样的,我需要在运行时根据SVN的状态动态控制PropertyGrid中的属性的读写控制。以前的做法比较简单,直接是PropertyGrid.Enabled(false)。这样的坏处是完全使Grid完全失效,连滚动条也不可用了,不便于查看属性。后来上网查阅相关的资料,网上有比较的是同一篇文章的复制,原文出处我已经找不到了。先把原文贴出来如下:

大家知道在类的某个属性中加[ReadOnlyAttribute(true)]声明标记后,此类的对象的这个属性在PropertyGrid中就表现为灰色不可更改,请问大家有没有什么办法动态地让这个属性在PropertyGrid中的显示变为可读写么?   
  以下的方法试过,不好用   
  1、想在程序里改声明标记,可是不行   
  2、另外写个类,同样的属性标记为[ReadOnlyAttribute(false)],然后重新selectobject,可是太复杂了。

用反射可以实现动态改变,只读、可见等等,这些属性都可以改变。

以下两个方法分别实现可见性和只读属性的动态改变:

void   SetPropertyVisibility(object   obj,   string   propertyName,   bool   visible)   
  {   
  Type   type   =   typeof(BrowsableAttribute);   
  PropertyDescriptorCollection   props   =   TypeDescriptor.GetProperties(obj);   
  AttributeCollection   attrs   =   props[propertyName].Attributes;   
  FieldInfo   fld   =   type.GetField("browsable",   BindingFlags.Instance   |   BindingFlags.NonPublic);   
  fld.SetValue(attrs[type],   visible);   
  }

void   SetPropertyReadOnly(object   obj,   string   propertyName,   bool   readOnly)   
  {   
  Type   type   =   typeof(System.ComponentModel.ReadOnlyAttribute);   
  PropertyDescriptorCollection   props   =   TypeDescriptor.GetProperties(obj);   
  AttributeCollection   attrs   =   props[propertyName].Attributes;   
  FieldInfo   fld   =   type.GetField("isReadOnly",   BindingFlags.Instance   |   BindingFlags.NonPublic   |   BindingFlags.CreateInstance);   
  fld.SetValue(attrs[type],   readOnly);   
  }

使用时,SetPropertyVisibility(obj,   "名称",   true);   
  obj指的就是你的SelectObject,   “名称”是你SelectObject的一个属性   
  当然,调用这两个方法后,重新SelectObject一下,就可以了

心得:

(1)如果对属性框中所有属性一起进行控制,可以不添加 [ReadOnlyAttribute(false)]标记,propertyName可以是任何属性名称。[注:这里讲得很不清楚]

(2)如果仅仅对某一个属性进行控制,则必须在每个属性的描述中添加 [ReadOnlyAttribute(false)]标记。propertyName必须是所要控制的属性名。

原文中提到的思路是在运行时,通过反射的方式修改每一个Property的ReadOnlyAttribute。只是心得那里説不很不清楚,要对整个对象而非具体的属性进行控制时怎么办。

我的第一个想法是遍历所有的Property,对每一个都设置ReadOnly,但是这样是错误的,而且有副作用。后来经过试验,我直接对PropertyGrid的Object设置ReadOnly。

 private void button1_Click(object sender, EventArgs e)
{
Type readonlyType = typeof(System.ComponentModel.ReadOnlyAttribute);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(propertyGrid1.SelectedObject);
FieldInfo fld = readonlyType.GetField("isReadOnly", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.CreateInstance);
AttributeCollection attrs = TypeDescriptor.GetAttributes(propertyGrid1.SelectedObject);
fld.SetValue(attrs[typeof(ReadOnlyAttribute)], gridReadOnly);
gridReadOnly = !gridReadOnly;
}

这里説一下,在找解决办法的时候,还去顺便了解了一下c#在运行时,动态添加Attribute的内容,这个内容留下次再记录好了。

还找到一篇讲反射可以通过FieldInfo.SetValue设置任何字段的值的文章:http://www.cnblogs.com/Laser_Lu/archive/2004/08/01/29171.html

第2点是PropertyGrid中使用TypeConverter

PropertyGrid中对于自定义的类型显示支持有限,最好是自己去实现自己的TypeConverter,把类型转换来进行显示。我写了一个简单的例子,把List类型转换成string。

 public class MyColorConverter : TypeConverter
{
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value == null)
{
return new List<int>();
}
string stringValue = value as string;
if (stringValue != null)
{
List<int> result = new List<int>();
string[] vs = stringValue.Split(new char[] { ',' });
foreach (string eachString in vs)
{
result.Add(int.Parse(eachString));
}
return result;
}
else
{
return base.ConvertFrom(context, culture, value);
}
} public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
} public override System.ComponentModel.PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributes)
{
throw new Exception("The method or operation is not implemented.");
} public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
List<int> list = value as List<int>;
if (list != null && list.Count > )
{
StringBuilder sb = new StringBuilder();
foreach (int v in list)
{
sb.AppendFormat("{0},", v);
}
sb.Remove(sb.Length - , );
return sb.ToString();
}
return "";
}
else
{
return base.ConvertTo(context, culture, value, destinationType);
}
} public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
}
     private List<int> color1 = new List<int>();
[Category("main")]
[DisplayName("颜色1")]
[TypeConverter(typeof(MyColorConverter))]
public List<int> Color1
{
get { return color1; }
set { color1 = value; }
}

ConvertFrom函数会在PropertyGrid中的字符串被修改保存后被调用

ConvertTo函数则是在最初显示PropertyGrid以及对List进行修改之后被调用

两点C#的propertyGrid的使用心得的更多相关文章

  1. 两点C#的propertyGrid的使用心得【转】

    源文:http://www.cnblogs.com/bicker/p/3318934.html 最近接触C#的PropertyGrid比较多,得到了两个小心得记录一下. 第1点是关于控制Propert ...

  2. C# PropertyGrid控件应用心得

    何处使用 PropertyGrid 控件 在应用程序中的很多地方,您都可以使用户与 PropertyGrid 进行交互,从而获得更丰富的编辑体验.例如,某个应用程序包含多个用户可以设置的“设置”或选项 ...

  3. C# PropertyGrid控件应用心得 【转】

    源文 : http://blog.csdn.net/luyifeiniu/article/details/5426960 c#stringattributesobjectmicrosoftclass ...

  4. 关于CSS中float的两点心得以及清除浮动的总结

    对一个元素运用float后,该元素将脱离正常文档流,这意味着: 1. 运用float后,该元素不再影响父元素的高度,如果一个元素的所有子元素都是float的话,那么该元素的高度是0,这样后面元素渲染的 ...

  5. PropertyGrid控件由浅入深(二):基础用法

    目录 PropertyGrid控件由浅入深(一):文章大纲 PropertyGrid控件由浅入深(二):基础用法 控件的外观构成 控件的外观构成如下图所示: PropertyGrid控件包含以下几个要 ...

  6. C# 如何定义让PropertyGrid控件显示[...]按钮,并且点击后以下拉框形式显示自定义控件编辑属性值

    关于PropertyGrid控件的详细用法请参考文献: 1.C# PropertyGrid控件应用心得 2.C#自定义PropertyGrid属性 首先定义一个要在下拉框显示的控件: using Sy ...

  7. windows类书的学习心得(转载)

    原文网址:http://www.blogjava.net/sound/archive/2008/08/21/40499.html 现在的计算机图书发展的可真快,很久没去书店,昨日去了一下,真是感叹万千 ...

  8. 百度api使用心得体会

    最近项目中在使用百度地图api,对于其中的一些有用的点做一些归纳整理,如有不对的地方,欢迎各位大神纠正指出. 一定要学会查找百度地图api提供的类参考网站:http://lbsyun.baidu.co ...

  9. System.Windows.Forms.PropertyGrid的使用

    PropertyGrid 控件简介 .NET 框架 PropertyGrid 控件是 Visual Studio .NET 属性浏览器的核心.PropertyGrid 控件显示对象或类型的属性,并主要 ...

随机推荐

  1. javascript防止SQL注入

    <SCRIPT language="javascript">function Check(theform){  if (theform.UserName.value== ...

  2. Steam即将正式加入人民币支付(转)

    Valve将在2015年Q4和2016年Q1加入一批新的货币结算支持,其中包括了人民币,这意味着以后玩家将无需在跳转支付平台后并通过美元结算.这对中国玩家来说是喜是忧? 本文由爱玩网整理报道,转载请保 ...

  3. mac 配置Python集成开发环境(Eclipse +Python+Pydev)

    1.下载Mac版64位的Eclipse. 进入到Eclipse官方网站的下载页面(http://www.eclipse.org/downloads/),我选择了下图所示的软件包, 浏览器在下载过程中使 ...

  4. ansible playbook最佳实践

    本篇主要是根据官方翻译而来,从而使简单的翻译,并没有相关的实验步骤,以后文章会补充为实验步骤,此篇主要是相关理论的说明,可以称之为中文手册之一,具体内容如下: Ansible playbooks最佳实 ...

  5. 设计模式 命令-Command

    命令-Command 当要向不同类的对象发出相同的请求时,可以将接收者和他的动作封装进一个命令对象.这样调用者只和命令产生依赖.而不会和众多的接收者发生依赖. Head First例子 要设计一款遥控 ...

  6. static public和 public static 区别

    static:加static 的是静态成员,不能实例化在你运行的时候他自己在内存中开辟了块空间,不用在new, 有点像全局变量,如果不用你必须去 实例化(new)才能用 static是静态的意思,pu ...

  7. 棒棒的毛笔字PS教程

    跟大家分享一下毛笔字怎么做出来的,主要通过字体和素材叠加,十分简单,喜欢的一起练习.做完记得交作业. 先看看最终效果: 在网上是不是经常看这些碉堡了的毛笔感觉是不是很羡慕啊,现在我就教大家怎么做出这样 ...

  8. 移动端的日期插件 mobiscroll 2.14.4 破解版

    官方报价695美元 http://mobiscroll.com/pricing 这个 mobiscroll 2.14.4 破解版 包括datetime和calendar组件,包括mobiscroll和 ...

  9. 【WPF】ContentControl Style定义与使用出现问题后 -- 引发的思考

    一.背景  使用WPF的朋友,大家都很喜欢采用定义控件的公共样式,以便整个框架对该资源的使用,好处就是可以达到代码复用.系统风格统一等: 1. 定义资源       <Style TargetT ...

  10. Hadoop学习之--Fair Scheduler作业调度分析

    Fair Scheduler调度器同步心跳分配任务的过程简单来讲会经历以下环节: 1. 对map/reduce是否已经达到资源上限的循环判断 2. 对pool队列根据Fair算法排序 3.然后循环po ...