txtControl1
。每当用户添加以下自定义文本框之一时,其名称应默认为
txtControl
。如何实现?
我的测试后,InamecReationservice确实可以实现您想要的效果。您可以参考以下步骤:1:基于.NET Framework的创建Windows表单控制库项目。
2:在项目中添加自定义控制类CustomTextBox:
using System.ComponentModel;
using System.Windows.Forms;
namespace CustomControlDemo
{
// Specify the designer as the CustomTextBoxDesigner that we will implement later
[Designer(typeof(CustomTextBoxDesigner))]
public class CustomTextBox : TextBox
{
// You can add other custom logic here
}
}
3:添加CustomTextBoxDesigner类以实现自定义设计器:
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Windows.Forms.Design;
namespace CustomControlDemo
{
public class CustomTextBoxDesigner : ControlDesigner
{
public override void Initialize(IComponent component)
{
base.Initialize(component);
IServiceContainer serviceContainer = (IServiceContainer)GetService(typeof(IServiceContainer));
if (serviceContainer != null)
{
INameCreationService existingService = serviceContainer.GetService(typeof(INameCreationService)) as INameCreationService;
if (!(existingService is CustomNameCreationService))
{
serviceContainer.RemoveService(typeof(INameCreationService), true);
serviceContainer.AddService(typeof(INameCreationService), new CustomNameCreationService(), true);
}
}
}
}
}
4:添加CustomNamecReationservice类以实现自定义
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
namespace CustomControlDemo
{
public class CustomNameCreationService : INameCreationService
{
public string CreateName(IContainer container, Type dataType)
{
Debug.WriteLine($"CreateName called for type: {dataType.Name}");
if (container == null)
throw new ArgumentNullException(nameof(container));
if (dataType == null)
throw new ArgumentNullException(nameof(dataType));
string baseName = "txtControl";
int index = 1;
while (container.Components[baseName + index] != null)
{
index++;
}
string newName = baseName + index;
Debug.WriteLine($"Generated name: {newName}");
return newName;
}
public bool IsValidName(string name)
{
return !string.IsNullOrEmpty(name);
}
public void ValidateName(string name)
{
if (!IsValidName(name))
throw new Exception("Invalid name: " + name);
}
}
}
5:保存文件并生成解决方案。创建一个新的Windows表单应用程序项目(.NET Framework),并刚刚引用控制库项目。打开表单设计师。从工具箱中查找CustomTextbox并将其拖放。
6:效应图:要注意的是:与.NET Framework Legacy Designer不同,在Winforms Designer的.NET版本中,InameCreationService似乎未使用或未正确注册。