Big*_*ian 8 c# code-generation windows-forms-designer visual-studio winforms
我们实施了新的编码标准,要求我们的私人会员拥有领先的下划线.像这样:
private System.Windows.Forms.Label _label;
Run Code Online (Sandbox Code Playgroud)
不幸的是,当您将新标签拖到表单上时,VS将在下面输出默认值:
private System.Windows.Forms.Label label1;
Run Code Online (Sandbox Code Playgroud)
有没有办法将默认值更改为:
private System.Windows.Forms.Label _label1;
Run Code Online (Sandbox Code Playgroud)
这适用于所有控件,而不仅仅是标签,是的,它们将从代码中使用.
干杯,
普拉门
Lex*_* Li 11
我个人认为自动生成的代码应该被排除在任何编码指南之外等等.除非生成器有错误,否则在大多数情况下忽略它们是安全的.
请与编写该编码指南的人进行辩论并询问他.他们要排除生成的代码.
小智 5
我知道这是一个老问题,但我最近一直在与定制设计师合作,我有一个适合您想要的解决方案。将此类添加到您的项目中:
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace WindowsFormsApplication1
{
[Designer(typeof(BaseFormDesigner), typeof(IRootDesigner))]
public class BaseForm : Form
{
public BaseForm()
{
}
}
public class BaseFormDesigner : DocumentDesigner
{
public override void Initialize(IComponent component)
{
base.Initialize(component);
var service = GetService(typeof(IComponentChangeService)) as IComponentChangeService;
service.ComponentAdded += service_ComponentAdded;
}
private void service_ComponentAdded(object sender, ComponentEventArgs e)
{
if (e.Component is Control && !(e.Component is Form)) {
var control = (Control)e.Component;
if (!control.Name.StartsWith("_")) {
var service = GetService(typeof(IComponentChangeService)) as IComponentChangeService;
PropertyDescriptor desc = TypeDescriptor.GetProperties(control)["Name"];
service.OnComponentChanging(e.Component, desc);
string oldValue = control.Name;
string newValue = "_" + oldValue;
desc.SetValue(control, newValue);
service.OnComponentChanged(e.Component, desc, oldValue, newValue);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后将基本表单类从 Form 更改为 BaseForm:
using System;
namespace WindowsFormsApplication1
{
public partial class Form1 : BaseForm
{
public Form1()
{
InitializeComponent();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在重新编译项目之前关闭所有表单设计器,然后重新打开它并尝试添加一个控件,其名称将以下划线开头。