【问题标题】:How can I use a class instead of creating multiple methods?如何使用一个类而不是创建多个方法?
【发布时间】:2019-09-13 22:45:46
【问题描述】:

我目前正在开发一个 WinForms 应用程序,我希望用户单击一个按钮,然后更改按钮文本。我有 11 个按钮,为每个按钮设置 MouseUpMouseDownClick 的方法会导致大量工作和重复非常相似的代码。

我做了一个类,但不知道如何处理用户点击的按钮。

public class AddButton 
    {
        public int Count { get; set; }

        private void Button_Click(object sender, EventArgs e)
        {
            Count++;
            ?ProductButton?.Text = Count + " Added";
        }
    }

如果需要,请单击this 链接下载完整的 WinForms 项目。

【问题讨论】:

    标签: c# winforms class


    【解决方案1】:

    我的做法:

    Button b = (Button)sender;
    b.BackColor = DashboardColors.EM_EditingTextBoxBackground;
    b.Text = "Save";
    

    将 'sender' 转换为适当的类型,然后您就可以正常使用它了。

    这应该可行:

    public class AddButton 
    {
        public int Count { get; set; }
    
        private void Button_Click(object sender, EventArgs e)
        {
            AddButton ab = (AddButton)sender;
    
            Count++;
            ab.Text = Count + " Added";
        }
    }
    

    如果 AddButton 派生自 Button-

    public class AddButton : Button
    

    因为'Text'是基类的一个属性;将发件人转换为(按钮)也应该可以。

    【讨论】:

    • 如何设置按钮是AddButton 类的实例?
    • public class AddButton { public int Count { get; set; } private void Button_Click(object sender, EventArgs e) { AddButton ab = (AddButton)sender; Count++; ab.Text = Count + " Added"; } }
    • 很抱歉问了这么多问题,但我找不到真正调用Button_Click 方法的方法。我必须在自动生成的 WinForms 中调用它吗?这仍然会导致必须写下 33 种不同的方法。我希望有可能让继承完成所有这些功能的工作......编辑:我应该发布一个新问题吗?我原来的问题得到了回答。
    • @hjknvcaesdbuihjase AddButton 是从按钮派生的类吗?如果是 - 在 AddButton 构造函数中将点击处理程序方法分配给它的事件...public AddButton() { this.click += new System.EventHandler(this.Button_Click); } 如果不是,它会变得更复杂。如果不知道更多关于你在做什么,我不能更具体。
    猜你喜欢
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2013-09-06
    • 1970-01-01
    相关资源
    最近更新 更多