【问题标题】:C# assigning several buttons to the same methodC#将多个按钮分配给同一个方法
【发布时间】:2017-05-29 16:04:12
【问题描述】:

我正在尝试使用 Win8 GUI 构建一个简单的“HangMan”游戏。我在屏幕上构建了带有 26 个按钮的 GUI,每个按钮代表一个字母。

我想将所有按钮连接到相同的方法,该方法检查按下的按钮的值是否与所选单词中的字母之一匹配。我已经查看了这个问题的答案,它应该对我有所帮助,但我认为一个区别是我的游戏中的所有逻辑和方法都在不同的类上,即“游戏管理器”类。

How can I subscribe multiple buttons to the same event handler and act according to what button was clicked?

另外,我不明白如何使用此解决方案,我将分配所有按钮的方法将知道按下了哪个按钮。我希望我能清楚地解释我的情况,如果没有,我可以提供部分代码以便更好地理解。

【问题讨论】:

  • 我会反转术语:如何将相同的方法分配给几个按钮的事件处理程序。答:就像为一个人做一样,但总是使用相同的方法名称。然后使用sender 参数(强制转换为Button)来辨别哪个按钮触发了事件..

标签: c# winrt-xaml controls


【解决方案1】:

这是你想要的基本方法:

    static string key = "Level solution";
    char[] chars = key.ToCharArray();
    void check (object sender)
    {
        var button = sender as Button;
        character = Convert.ToChar(button.Text);
        int i = 0;
        foreach (char c in chars)
        {
            //checks every character to mark them
            if (c == character)
            {
                chars[i] = ' ';
                //Makes character unusable for later use

                //Anything you want now for true letters, for example showing pics or adding them to a label
            }
            i++;
        }
        //checks every character of key again, to see if player is won
        int count = 0;
        foreach (char c in chars) {
            if (c != ' ') count++;
            //Adds a number for anything expect space
        }

        if (count == 0)
        {
            MessageBox.Show("You won!");
        }

    }

您可以将其粘贴到代码之上,然后在任何按钮中仅使用此代码:

check(sender);

【讨论】:

  • 感谢您的回答!但我仍然不明白单击按钮的值输入的位置,以便此方法或我将其与单词的字符之一进行比较。我将所有按钮注册到一个触发其他类中的 CheckLetter 函数的事件单击。但是我如何通过这个链传递按钮的值以使用该方法匹配它。
  • private void CheckLetter_Click(object sender, RoutedEventArgs e) { Mng.CheckLetter(); } public bool CheckLetter() { for (int i = 0; i < txtBlkArr.Length; i++) { if (btnA.Content == txtBlkArr[i]) { txtBlkArr[i].Visibility = Visibility.Visible; } else { //StartHanging(); return false; } } return true; }
  • 现在使用已编辑的方法。这个应该做你想做的。 *尚未测试
  • 谢谢!我现在明白了,终于有人解释了,让我学习新的东西,比如拒绝投票和什么都不做。我将“Var button = sender as Button”应用到我的代码中,这正是我想要的!
  • 不客气,老兄,投反对票 XD。总是有人不阅读就对所有内容投反对票:P
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多