0

次のように、C# Windows フォーム コントロール ライブラリとコードを使用して、複合コントロールを開発しました。

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が 1 つだけありますGroupBoxmyGroupBox

private System.Windows.Forms.GroupBox myGroupBox;

C# Windows フォーム アプリケーションであるテスト プログラムがありmyGroupBox、プロパティ ウィンドウでの名前を変更するmyGroupBoxと、入力した名前が のテキストになることを確認したいと思います。プロパティウィンドウに名前を入力するValuemyGroupBox、デザイナーでテキストが変更されます。スクリーンショットは次のとおりです。 ここに画像の説明を入力

しかし、テスト プログラムを再構築するか、実行時にテキストmyGroupBoxが消えると、スクリーンショットは次のようになります。

ここに画像の説明を入力

コードをどうすればいいですか?ありがとう

4

1 に答える 1

1

したがって、問題は、Namea Control(またはUserControl) の が構築後に空になることです。ユーザーが指定してリソースに保存された名前が に設定され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);
    }
}

そのため、リソースから取得された名前 (たとえば、再構築/デザイナーの再オープン後) がここで再度設定され、. としても設定されmyGroupBox.Textます。

それが役立つことを願っています。

于 2016-01-21T13:33:40.827 に答える