用户操作后从用户控件返回值

Sha*_*air 3 .net c# user-controls winforms

基本上我需要 Form.ShowDialog() 提供的相同的东西,但需要一个 UserControl。

在一个 winform 中,我加载了一个 UserControl,它应该允许用户从列表中选择一个项目,并将其返回给调用者。

例如:

var item = myUserControl.SelectItem();
Run Code Online (Sandbox Code Playgroud)

显然,从控件的方法返回非常简单。但是我怎样才能让它等到用户使用控件执行所需的操作?

我可以订阅控件的一个事件,但是这个路径并不理想。

简而言之,我希望 UserControl 的方法在用户单击其上的特定按钮后返回。

Bra*_*Rem 5

简而言之,UserControl 实际上只是一个自定义控件,就像您在 WinFrom 上放置 aTextBox或 aListBox一样,您将 UserControl 放置在窗体上。

像对待任何其他控件一样对待您的 UserControl,例如TextBoxListBox

所以,就像你从获得的价值TextBox通过TextBox.TextSelectedValueSelectedItemListBox,你会叫您的用户控件的方法返回的SelectedItem。

通常,当单击 OK 按钮或关闭表单时,您将在代码中遍历表单的每个控件以获取它们的值。据推测,您也会进行一些验证以确保输入了正确的值。

因此,当您的表单被接受时,您将调用 UserControl 的方法来获取所选项目。您不必订阅事件来等待它发生。同样,就像对待普通ListBox.

编辑:

现在更多地了解您的问题的性质,这是我的答案:

假设您有一个如下所示的 UserControl:

选择从列表用户控件

在后面的代码中,您将不得不设置一个事件来监视何时在 UserControl 内单击了 OK 按钮。此事件还将通知订阅者用户在您的列表中选择了什么:

public partial class SelectFromListUserControl : UserControl
{
    public class SelectedItemEventArgs : EventArgs
    {
        public string SelectedChoice { get; set; }
    }

    public event EventHandler<SelectedItemEventArgs> ItemHasBeenSelected;

    public SelectFromListUserControl()
    {
        InitializeComponent();
    }

    private void btnOK_Click(object sender, EventArgs e)
    {
        var handler = ItemHasBeenSelected;
        if (handler != null)
        {
            handler(this, new SelectedItemEventArgs 
                { SelectedChoice = listBox1.SelectedItem.ToString() });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的主表单上,您将拥有类似于以下内容的代码模式。

  1. 应该有一个例程来创建或显示这个特殊的用户控件。
  2. 它将钩住用户控件中的事件,以便通知主窗体。
  3. 它将绘制用户控件。
  4. 事件处理程序将检索在用户控件中选择的值,然后清除用户控件和/或调出另一个用户控件。

    private void ShowSelectFromListWidget()
    {
        var uc = new SelectFromListUserControl();
        uc.ItemHasBeenSelected += uc_ItemHasBeenSelected;
    
        MakeUserControlPrimaryWindow(uc);
    }
    
    void uc_ItemHasBeenSelected(object sender, 
                         SelectFromListUserControl.SelectedItemEventArgs e)
    {
        var value = e.SelectedChoice;
    
        ClosePrimaryUserControl();
    }
    
    private void MakeUserControlPrimaryWindow(UserControl uc)
    {
        // my example just puts in in a panel, but for you
        // put your special code here to handle your user control management 
        panel1.Controls.Add(uc);
    }
    
    private void ClosePrimaryUserControl()
    {
        // put your special code here to handle your user control management 
        panel1.Controls.Clear();
    }
    
    Run Code Online (Sandbox Code Playgroud)