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

如何为Visual Studio扩展创建包含文本框的属性页

创建带文本框的Visual Studio扩展属性页

1. 搭建基础项目结构

  • 打开Visual Studio,创建一个VSIX项目;如果要针对特定项目类型做属性页,可搭配添加项目模板扩展,或直接基于PropertyPage类实现。
  • 引用必要程序集:Microsoft.VisualStudio.Shell.15.0(对应你的VS版本)、Microsoft.VisualStudio.Shell.Interop等。

2. 实现属性页核心类

以项目属性页为例,创建继承自PropertyPage的类,负责加载、保存属性值:

using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using System;
using System.Runtime.InteropServices;

[Guid("生成的唯一GUID")]
public class CustomPropertyPage : PropertyPage
{
    private CustomPropertyPageControl _control;

    protected override void CreatePropertyPage()
    {
        _control = new CustomPropertyPageControl();
        this.Control = _control;
    }

    public override void LoadSettings()
    {
        // 从项目读取已保存的设置,赋值给文本框
        var projectValue = this.Project.Properties.Item("CustomSetting").Value?.ToString();
        _control.InputTextBox.Text = projectValue ?? string.Empty;
    }

    public override void SaveSettings()
    {
        // 将文本框内容保存到项目属性
        this.Project.Properties.Item("CustomSetting").Value = _control.InputTextBox.Text;
    }
}

3. 创建带文本框的控件

用WinForms实现一个用户控件,包含文本框:

using System.Windows.Forms;

public class CustomPropertyPageControl : UserControl
{
    public TextBox InputTextBox { get; private set; }

    public CustomPropertyPageControl()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        this.InputTextBox = new TextBox();
        this.SuspendLayout();

        // 文本框布局设置
        this.InputTextBox.Location = new System.Drawing.Point(15, 15);
        this.InputTextBox.Size = new System.Drawing.Size(280, 23);
        this.InputTextBox.PlaceholderText = "请输入自定义内容";

        // 控件整体设置
        this.Controls.Add(this.InputTextBox);
        this.Size = new System.Drawing.Size(310, 80);
        this.ResumeLayout(false);
        this.PerformLayout();
    }
}

如果偏好WPF,可创建WPF UserControl,添加<TextBox>元素,通过ElementHost托管到属性页中,逻辑一致。

4. 注册属性页

在Package类中注册属性页,关联到目标项目类型:

using Microsoft.VisualStudio.Shell;
using System;

[PackageRegistration(UseManagedResourcesOnly = true)]
[Guid("Package的唯一GUID")]
[ProvideObject(typeof(CustomPropertyPage))]
// 替换项目类型GUID,比如C#项目是FAE04EC0-301F-11D3-BF4B-00C04F79EFBC
[ProvidePropertyPage(typeof(CustomPropertyPage), "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC", "自定义属性", 0, 0, true)]
public class CustomPackage : Package
{
    protected override void Initialize()
    {
        base.Initialize();
    }
}

5. 测试扩展

  • 按F5启动实验性VS实例,创建或打开对应类型的项目。
  • 右键项目→属性,就能看到新增的“自定义属性”标签页,文本框可输入内容,保存后重启项目,设置会持久化。

关键提示

  • 所有GUID需唯一,可通过VS工具→创建GUID生成。
  • 若项目没有CustomSetting属性,需先在项目文件中定义,或通过DTE对象动态创建。
  • 用WPF控件时,要确保ElementHost正确托管WPF内容,避免布局异常。

内容的提问来源于stack exchange,提问作者Ken Kazinski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 11:44:56