在设计时更改自定义控件的默认Text属性 [英] Change custom control default Text property at design time
问题描述
我创建了一个用户控件。基本上是一个带有一些自定义属性的按钮。
I created a user control. It's basically a button with some custom properties.
public partial class CustomButton : Button {
// My custom properties, constructor and events
}
每次我添加此 CustomButton
在窗体上,其默认 Text
值设置为 customButtonX ,其中X为1、2、3 、。 ..
Everytime I add this CustomButton
on a form, its default Text
value is set to "customButtonX", where X is 1, 2, 3, ...
如何更改此值?我希望它是 buttonX (X = 1、2、3 ...)。
How can I change this value? I would like it to be "buttonX" (X = 1, 2, 3...).
编辑:当我也通过设计视图在表单上添加按钮时,我希望这个技巧(或必须要做的任何事情)有效。意思是当我从工具箱中将 CustomButton
拖放到窗体上时,其 Text
值应为 buttonX 。
EDIT : I would like the trick (or whatever it is I have to do) to be active when I add a button on a form via the design view also. Meaning when I drag-drop a CustomButton
from my toolbox to a form, its Text
value should be "buttonX".
推荐答案
将控件从工具箱拖到窗体上时,会触发一些事件。在您的情况下,您必须订阅将控件的text属性从String.Empty更改为默认名称时更改的默认名称。为此,您必须在将控件添加到表单之前获取公开这些事件的服务(IComponentChangeService的实现)。可以通过覆盖控件的Site属性来完成此操作。修改示例,您可以在此处,这类代码应该可以工作:
When you drag a control from the Toolbox to a form there are some events that are triggered. In your case you have to subscribe to the one that is fired when the text property of your control is changed from String.Empty to the default name and change it. To do this you have to get the service that exposes these events (an implementation of IComponentChangeService) before the control is added to the form. This can be done overriding the Site property of your control. Modifying the example that you can find here, this kind of code should work:
private IComponentChangeService _changeService;
public override System.ComponentModel.ISite Site
{
get
{
return base.Site;
}
set
{
_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
if (_changeService != null)
_changeService.ComponentChanged -= new ComponentChangedEventHandler(OnComponentChanged);
base.Site = value;
if (!DesignMode)
return;
_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
if (_changeService != null)
_changeService.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged);
}
}
private void OnComponentChanged(object sender, ComponentChangedEventArgs ce)
{
CustomButton aBtn = ce.Component as CustomButton;
if (aBtn == null || !aBtn.DesignMode)
return;
if (((IComponent)ce.Component).Site == null || ce.Member == null || ce.Member.Name != "Text")
return;
if (aBtn.Text == aBtn.Name)
aBtn.Text = aBtn.Name.Replace("customButton", "button");
}
这篇关于在设计时更改自定义控件的默认Text属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!