C# 复合控件将在设计和 运行 时间丢失名称

C# Composite Control will lose name at design and run time

我用C#开发了一个复合控件Windows Forms Control Library,代码如下:

public partial class MyControl : UserControl
{
    public event EventHandler NameChanged;
    protected virtual void OnNameChanged()
    {
        EventHandler handler = NameChanged;
        if (handler != null) handler(this, EventArgs.Empty);
    }

    private void WhenNameChanged(object sender , EventArgs e)
    {
        this.myGroupBox.Text = this.Name;
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        IComponentChangeService changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
        if (changeService == null) return; // not provided at runtime, only design mode

        changeService.ComponentChanged -= OnComponentChanged; // to avoid multiple subscriptions
        changeService.ComponentChanged += OnComponentChanged;
    }

    private void OnComponentChanged(object sender, ComponentChangedEventArgs e)
    {
        if(e.Component == this && e.Member.Name == "Name")
        {
            OnNameChanged();
        }
    }

    public MyControl()
    {
        InitializeComponent();
        this.NameChanged += new EventHandler(this.WhenNameChanged);
    }
}

MyControl 只有一个 GroupBox 控件名为 myGroupBox

private System.Windows.Forms.GroupBox myGroupBox;

我有一个测试程序,它是一个 C# Windows Forms 应用程序,当我在属性 window 中更改 myGroupBox 的名称时,我希望看到文本myGroupBox 将是我输入的名称。所以我在属性 window 中输入了一个名称 ValuemyGroupBox,文本将在设计器中更改,这是屏幕截图:

但是当我重建测试程序或者在运行时候myGroupBox的文字会消失,截图如下:

我应该如何处理我的代码?谢谢

所以问题是一个Control(或UserControl)的Name构造后为空。您给的名称存储在资源中将设置在OnLoad.
所以你的解决方案可能是用这样的东西覆盖 OnLoad

public class MyControl : UserControl
{
    // ... the code so far

    // override OnLoad
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        myGroupBox.Text = Name; // or WhenNameChanged(this, EventArgs.Empty);
    }
}

因此从资源中获取的名称(例如在 rebuild/reopen 设计师之后)将再次设置在这里,因此也设置为 myGroupBox.Text

希望对您有所帮助。