c#获取从用户控件中单击的按钮的值

时间:2016-03-13 05:15:47

标签: c# winforms user-controls

我有用户控件并将其命名为ucMilkshake,我的主要表单Form1每个都有一组按钮。我将项目按钮放在ucMilkshakeForm1上的数量(1,2,3,4,5,6,7,8,9)按钮上,用户需要先点击btnMilkshake ucMilkshake panel会在Form1listview内弹出,他们会在选择项目数量之后看到项目清单,然后选择项目数量显示在Form1

中的if statement

但我无法获得用户控件中点击按钮的价值,希望有人可以使用public partial class ucMilkshake : UserControl { int clickcount = 0; private static ucMilkshake _instance; public static ucMilkshake Instance { get { if (_instance == null) _instance = new ucMilkshake(); return _instance; } } public ucMilkshake() { InitializeComponent(); } public string MS1 { get { return button11.Text; } } private void button1_Click(object sender, EventArgs e) { clickcount - 1; } private void button2_Click(object sender, EventArgs e) { clickcount = 2; } }` 来解决我的问题,因为我有一组按钮

继承我的代码:

用户控制

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }


    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void btnMilkshake_Click(object sender, EventArgs e)
    {
        if (!mainPanel.Controls.Contains(ucMilkshake.Instance))
        {
            mainPanel.Controls.Add(ucMilkshake.Instance);
            ucMilkshake.Instance.Dock = DockStyle.Fill;
            ucMilkshake.Instance.BringToFront();
        }
        else
            ucMilkshake.Instance.BringToFront();
    }

    private void quantityOne_Click(Object sender, EventArgs e)
    {
        //here i want to use if statement to get the value of clicked button in user control

    private void quantityTwo_Click(Object sender, EventArgs e)
  }

Form1中

{{1}}

1 个答案:

答案 0 :(得分:1)

请勿在{{1​​}}中使用成员变量。而是创建一个可以在UserControl

中访问的公共属性
Form

然后在Form的click事件处理程序中,您可以像这样访问值:

public partial class ucMilkshake : UserControl
{
    private static ucMilkshake _instance;

    public int ClickCount { get; private set; }

    public static ucMilkshake Instance
    {
        get
        {
            if (_instance == null)
                _instance = new ucMilkshake();
            return _instance;
        }
    }

    public ucMilkshake()
    {
        InitializeComponent();
    }

    public string MS1
    {
        get
        {
            return button11.Text;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ClickCount -= 1;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        ClickCount = 2;
    }
}