You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Windows Forms PropertyGrid如何为分类本身设置Description描述文本

实现方案

标准WinForm的PropertyGrid控件没有内置为分类项设置描述文本的原生特性,可通过自定义特性+监听选中项变更事件的方式快速实现,具体步骤如下:

  1. 自定义分类描述特性
    首先新建一个可在类上多次标记的特性,用来存储分类名称和对应的帮助文本:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class CategoryDescriptionAttribute : Attribute
{
    /// <summary>
    /// 分类名称
    /// </summary>
    public string CategoryName { get; }
    /// <summary>
    /// 分类对应的帮助描述
    /// </summary>
    public string Description { get; }

    public CategoryDescriptionAttribute(string categoryName, string description)
    {
        CategoryName = categoryName;
        Description = description;
    }
}
  1. 给绑定的模型类加特性标记
    在你要绑定到PropertyGrid的类上,为每个分类加对应的描述特性:
// 为每个分类标记对应的描述
[CategoryDescription("Foo Category", "该分类下的所有属性都和Foo业务逻辑相关")]
public class Foo
{
    [Category("Foo Category")]
    [Description("Foo属性的帮助文本")]
    public string fooProperty { get; set; } = "";
}
  1. 监听PropertyGrid的选中项变更事件
    给PropertyGrid绑定SelectedGridItemChanged事件,当选中项为分类时,读取对应的自定义特性,修改底部帮助面板的内容:
private void propertyGrid1_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e)
{
    // 仅处理选中分类的场景
    if (e.NewSelection?.GridItemType != GridItemType.Category) return;
    
    string targetCategory = e.NewSelection.Label;
    object bindObj = propertyGrid1.SelectedObject;
    if (bindObj == null) return;

    // 读取绑定类上的分类描述特性
    var categoryDesc = bindObj.GetType()
        .GetCustomAttributes(typeof(CategoryDescriptionAttribute), false)
        .Cast<CategoryDescriptionAttribute>()
        .FirstOrDefault(attr => attr.CategoryName == targetCategory);

    if (categoryDesc == null) return;
    
    // 找到PropertyGrid内部的帮助面板控件赋值
    var helpPanel = propertyGrid1.Controls
        .OfType<Control>()
        .FirstOrDefault(c => c.Name == "DocComment");
    if (helpPanel == null) return;

    var titleLabel = helpPanel.Controls
        .OfType<Label>()
        .FirstOrDefault(l => l.Name == "DocCommentTitle");
    var descLabel = helpPanel.Controls
        .OfType<Label>()
        .FirstOrDefault(l => l.Name == "DocCommentDescription");

    if (titleLabel != null) titleLabel.Text = targetCategory;
    if (descLabel != null) descLabel.Text = categoryDesc.Description;
}

补充说明

如果你的PropertyGrid需要支持同时绑定多个对象(SelectedObjects属性赋值),只需调整事件逻辑,遍历所有绑定对象的特性,取公共的分类描述展示即可。


内容的提问来源于stack exchange,提问作者The Lemon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:06:07