日期:2009-01-20  浏览次数:20504 次

充分利用 .NET 框架的 PropertyGrid 控件
Mark Rideout
Microsoft Corporation


摘要:本文旨在帮助您了解 Microsoft .NET 框架中的 PropertyGrid 控件,以及如何针对您的应用程序自定义该控件。

适用于:
Microsoft® .NET® 框架
Microsoft® Visual Studio® .NET

目录
PropertyGrid 控件简介
创建 PropertyGrid 控件
何处使用 PropertyGrid 控件
选择对象
自定义 PropertyGrid 控件
显示复杂属性
为属性提供自定义 UI
小结

PropertyGrid 控件简介
如果您使用过 Microsoft® Visual Basic® 或 Microsoft Visual Studio .NET,那么您一定使用过属性浏览器来浏览、查看和编辑一个或多个对象的属性。.NET 框架 PropertyGrid 控件是 Visual Studio .NET 属性浏览器的核心。PropertyGrid 控件显示对象或类型的属性,并主要通过使用反射来检索项目的属性。(反射是在运行时提供类型信息的技术。)

下面的屏幕快照显示了 PropertyGrid 在窗体上的外观。



图 1:窗体上的 PropertyGrid

PropertyGrid 包含以下部分:

属性
可展开属性
属性类别标题
属性说明
属性编辑器
属性选项卡
命令窗格(显示控件设计器提供的设计器操作)
创建 PropertyGrid 控件
要使用 Visual Studio .NET 创建 PropertyGrid 控件,需要将该控件添加到工具箱中,因为默认情况下并不包含该控件。在 Tools(工具)菜单中,选择 Customize Toolbox(自定义工具箱)。在对话框中选择 Framework Components(框架组件)选项卡,然后选择 PropertyGrid。

如果您从命令行编译代码,请使用 /reference 选项并指定 System.Windows.Forms.dll。

以下代码显示了如何创建 PropertyGrid 控件并将其添加到窗体中。

' Visual Basic

Imports System
Imports System.Drawing
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Globalization

Public Class OptionsDialog
Inherits System.Windows.Forms.Form

Private OptionsPropertyGrid As System.Windows.Forms.PropertyGrid

Public Sub New()
MyBase.New()

OptionsPropertyGrid = New PropertyGrid()
OptionsPropertyGrid.Size = New Size(300, 250)

Me.Controls.Add(OptionsPropertyGrid)
Me.Text = "选项对话框"
End Sub
End Class


//C#

using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.Globalization;

public class OptionsDialog : System.Windows.Forms.Form
{
private System.Windows.Forms.PropertyGrid OptionsPropertyGrid;
public OptionsDialog()
{
OptionsPropertyGrid = new PropertyGrid();
OptionsPropertyGrid.Size = new Size(300, 250);

this.Controls.Add(OptionsPropertyGrid);
this.Text = "选项对话框";
}

[STAThread]
static void Main()
{
Application.Run(new OptionsDialog());
}
}
何处使用 PropertyGrid 控件
在应用程序中的很多地方,您都可以使用户与 PropertyGrid 进行交互,从而获得更丰富的编辑体验。例如,某个应用程序包含多个用户可以设置的“设置”或选项,其中一些可能十分复杂。您可以使用单选按钮、组合框或文本框来表示这些选项。但本文将逐步介绍如何使用 PropertyGrid 控件创建选项窗口来设置应用程序选项。上面所创建的 OptionsDialog 窗体即是选项窗口的开始。现在,我们创建一个名为 AppSettings 的类,其中包含映射到应用程序设置的所有属性。如果创建单独的类而不使用多个分散的变量,设置将更便于管理和维护。

' Visual Basic

Public Class AppSettings
Private _saveOnClose As Boolean = True
Private _greetingText As String = "欢迎使用应用程序!"
Private _maxRepeatRate As Integer = 10
Private _itemsInMRU As Integer = 4

Private _settingsChanged As Boolean = False
Private _appVersion As String = "1.0"

Public Property SaveOnClose() As Boolean
Get
Return _saveOnClose
End Get
Set(ByVal Value As Boolean)
SaveOnClose = Value
End Set
End Property

Public Property GreetingText() As String
Get
Return _greetingText
End Get
Set(ByVal Value As String)
_greetingText = Value
End Set
End Property

Public Property ItemsInMRUList() As Integer
Get