客户要写一个Visual Studio .NET的Add-in,需要在design time获取form上控件的值,以下是用Reflection的做法

     

VS.NET Add-in在Design time获取控件值       Dim win As Window = applicationObject.ActiveWindow
VS.NET Add-in在Design time获取控件值            
Dim d As ComponentModel.Design.IDesignerHost = win.Object
VS.NET Add-in在Design time获取控件值            iss 
= d.GetService(GetType(ComponentModel.Design.ISelectionService))
VS.NET Add-in在Design time获取控件值            
Dim c As ComponentModel.Component = iss.PrimarySelection
VS.NET Add-in在Design time获取控件值            
Dim pi As Reflection.PropertyInfo = CObj(c).GetType().GetProperty("Visible")
VS.NET Add-in在Design time获取控件值            
VS.NET Add-in在Design time获取控件值            
Dim val As Object = pi.GetValue(c, Nothing)
VS.NET Add-in在Design time获取控件值            
Dim tc As System.ComponentModel.TypeConverter = ComponentModel.TypeDescriptor.GetConverter(val)
VS.NET Add-in在Design time获取控件值            
MsgBox(c.Site.Name & "." & pi.Name & " = " & tc.ConvertToString(val))


这样做有一个问题,当我要取TextBox.Visible这类属性的时候,返回值永远为true,因为reflect的是designer中的textbox对象,它的visible值永远为true。正确的做法是通过PropertyDescriptorCollection来读取Properties window里面的值,代码如下:

VS.NET Add-in在Design time获取控件值 VS.NET Add-in在Design time获取控件值 VS.NET Add-in在Design time获取控件值
VS.NET Add-in在Design time获取控件值   
VS.NET Add-in在Design time获取控件值           
'query Properties
VS.NET Add-in在Design time获取控件值
            Dim properties As System.ComponentModel.PropertyDescriptorCollection
VS.NET Add-in在Design time获取控件值            properties 
= System.ComponentModel.TypeDescriptor.GetProperties(c)
VS.NET Add-in在Design time获取控件值            
Dim prop As System.ComponentModel.PropertyDescriptor
VS.NET Add-in在Design time获取控件值            prop 
= properties("Visible")
VS.NET Add-in在Design time获取控件值            
MsgBox(c.Site.Name & "." & prop.Name & " = " & prop.GetValue(c))
VS.NET Add-in在Design time获取控件值

本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利

相关文章:

  • 2022-12-23
  • 2021-10-29
  • 2021-12-03
  • 2021-09-25
  • 2022-12-23
  • 2022-02-26
  • 2022-03-08
猜你喜欢
  • 2021-06-10
  • 2021-08-04
  • 2021-12-14
  • 2021-10-27
  • 2022-01-16
  • 2021-05-28
相关资源
相似解决方案