且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在设计时更改自定义控件的默认Text属性

更新时间:2023-10-03 09:02:34

将控件从工具箱拖到窗体上时,会触发一些事件。在您的情况下,您必须订阅将控件的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");
    }