c# Winform Controls to VSTO Excel Addin 如何取回价值。

c# Winform Controls to VSTO Excel Addin How to get value back.

我是 VSTO Excel 插件的新手,我希望将 Winform 控件添加到 VSTO 项目。目前我的插件有一个功能区和一个按钮。单击按钮会打开一个 Windows 表单,其中有几个复选框和一个 "Done" 按钮。一旦用户点击完成,我想捕获用户选择的所有复选框。

这是我的丝带的样子:

"Split Data" 是按钮,单击它甚至会启动一个 Winform,如下所示:

private void btnSpltData_Click(object sender, RibbonControlEventArgs e)
        {
            FieldSelector fs = new FieldSelector();
            fs.ShowDialog();
        }

使用“完成”按钮,我正在关闭表单。我可以使用 checkbox.checked 属性 找出检查了哪个复选框,但我不确定如何将其发送回功能区中的 btnSpltData_Click 方法。

我怎样才能做到这一点?任何指针?

private void buttonDone_Click(object sender, EventArgs e)
        {
            this.Close();
        }

您已经通过调用 .ShowDialog(); 显示了表单,很好,这将破坏该行的代码,直到表单关闭。因此,只需在您的表单中添加一个 属性 ,您以后就可以阅读了。 小例子:

public class Ribbon
{
    private void btnSpltData_Click(object sender, RibbonControlEventArgs e)
    {
        FieldSelector fs = new FieldSelector();
        fs.ShowDialog();
        if (fs.DialogResult == DialogResult.OK) // Did user press the 'done' button? or did they exit using X
        {
            foreach (var checkedField in fs.CheckedFields)
            {
                // do stuff with the value
            }
        }
    }
}
public class FieldSelector :  Form
{
    // A property to read after the form has closed
    public List<string> CheckedFields 
    { 
         get; 
    } = new List<string>(); // Never null

    private void buttonDone_Click(object sender, EventArgs e)
    {
        // Retrieve all the Checkboxes that are a direct child of the form
        foreach (var control in Controls.OfType<CheckBox>())
        {
            if (control.Checked)
                CheckedFields.Add(control.Text); // Keep track of the Text value of the checked checkboxes
        }

        this.DialogResult = DialogResult.OK; // just for being neat when using ShowDialog()
        this.Close();
    }
}