簡體   English   中英

如何將焦點設置在自定義控件中的控件上?

[英]How to set focus on a control within a custom control?

我有一個包含文本框和按鈕的自定義控件。 我使用自定義控件作為ObjectListView中特定列的編輯控件。

在CellEditStarting事件上我做:

private void datalistViewProducts_CellEditStarting(object sender, CellEditEventArgs e)
{
    var ctl = (MyCustomControl)e.Control;
    e.Control = ctl;
}

ObjectListView的ConfigureControl方法已經調用了控件的Select方法。 如果我有一個直接從標准TextBox繼承的usercontrol,它工作正常。

所以我將以下代碼添加到我的usercontrol:

public new void Select()
{
    textBox.Select();
}

但是,如上所述具有用戶控件, Select方法不會將焦點移動到文本框。

我在這里錯過了什么?

您可以在CustomUserControl中創建一個方法,比如FocusControl(string controlName) ,然后調用此方法將控件聚焦在Custom Control中。

在自定義用戶控件中創建方法 -

public void FocusControl(string controlName)
    {
        var controls = this.Controls.Find(controlName, true);
        if (controls != null && controls.Count() == 1)
        {
            controls.First().Focus();
        }
    }

稱這種方法 -

//textBox1 is the name of your focussing control in Custom User Control
userControl11.FocusControl("textBox1");

使它最終工作的唯一方法是在usercontrol中添加以下代碼:

protected override void OnEnter(EventArgs e)
{
    base.OnEnter(e);
    textBox.Select();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM