Winforms如何通过触发其中一个来使两个用户控件同时工作

Winforms how to make two user controls work simultaneously by triggering either of them

我使用 Winforms 创建了一个带有两个按钮、一个标签和一个可浏览按钮的用户控件 属性。

    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "Button1 is clicked";
    }

    private void button2_Click(object sender, EventArgs e)
    {
        label1.Text = "Button2 is clicked";
    }

    public enum Type { StandAlone = 1, Parallel }
    private Type _defaultType = Type.StandAlone;

    [Browsable(true), DisplayName("Type")]
    public Type MyProperty { get { return _defaultType; } set { _defaultType = value; } }

现在我已将其中 4 个添加到我的表单中。

我希望做的是,如果用户为这些用户控件中的两个选择并行,那么这两个应该同时工作。

假设这 4 个用户控件分别命名为 ucControl1、ucControl2、ucControl3、ucControl4

如果ucControl1和ucControl2的类型属性设置为并行,那么在运行时如果用户点击ucControl1的button1,那么ucControl2的button1也应该触发Click事件,反之亦然。

这可能吗?我有哪些选择?

您可以作弊并在 UserControl 本身中保留一个 static UserControl 列表。将每个 UserControl 添加到其构造函数的列表中。然后你可以迭代它并要求每个并行 UserControl 单击同名按钮。

您必须做一些额外的整理工作以防止按钮无限地相互点击。这是一个简单的例子:

public partial class ucControl : UserControl
{

    private static bool suppressRecursion = false;
    private static List<ucControl> ucControls = new List<ucControl>();

    public ucControl()
    {
        InitializeComponent();

        ucControls.Add(this);
        button1.Click += (s, e) => ClickParallelButtons((Button)s);
        button2.Click += (s, e) => ClickParallelButtons((Button)s);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Console.WriteLine("button1 of " + this.Name + " clicked.");            
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Console.WriteLine("button2 of " + this.Name + " clicked.");
    }

    private void ClickParallelButtons(Button btn)
    {
        if (this._defaultType == Type.Parallel && !suppressRecursion)
        {
            suppressRecursion = true;
            foreach (ucControl uc in ucControls)
            {
                if (uc != this && uc._defaultType == Type.Parallel)
                {
                    Control ctlTarget = uc.Controls.Find(btn.Name, true).FirstOrDefault();
                    if (ctlTarget != null && ctlTarget is Button)
                    {
                        ((Button)ctlTarget).PerformClick();
                    }
                }
            }
            suppressRecursion = false;
        }            
    }

    public enum Type { StandAlone = 1, Parallel }
    private Type _defaultType = Type.StandAlone;

    [Browsable(true), DisplayName("Type")]
    public Type MyProperty { get { return _defaultType; } set { _defaultType = value; } }

}