0

我有以下代码,我为我的游戏级别菜单的每个按钮单击事件传递了一个参数。

    private void btnLevelVeryEasy_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.Navigate(new Uri("/GamePlay.xaml?parameter=0", UriKind.Relative));
    }

    private void btnLevelEasy_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.Navigate(new Uri("/GamePlay.xaml?parameter=1", UriKind.Relative));
    }

    private void btnLevelMedium_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.Navigate(new Uri("/GamePlay.xaml?parameter=2", UriKind.Relative));
    }

    private void btnLevelHard_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.Navigate(new Uri("/GamePlay.xaml?parameter=3", UriKind.Relative));
    }

    private void btnLevelInsane_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.Navigate(new Uri("/GamePlay.xaml?parameter=4", UriKind.Relative));
    }

我的问题是,如何通过让所有按钮触发一次单击事件并传递唯一参数来更优雅地做到这一点?就像是

    private void btnLevel_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.Navigate(new Uri("/GamePlay.xaml?parameter=[buttontag]", UriKind.Relative));
    }
4

2 回答 2

3

Sayse 几乎是对的,除了 .Name 应该在 () 之后:

string buttonName = ((Button)sender).Name;

            switch (buttonName)
            {
                case "button1":
                    MessageBox.Show("Button1 pressed");
                    break;
                case "button2":
                    MessageBox.Show("Button2 pressed");
                    break;
            }

编辑:

OP,你知道如何链接每个按钮上的事件吗?(在事件中,只需单击下拉菜单并选择先前创建的事件)

于 2013-01-30T07:57:56.483 回答
2

根据我的评论,根据您的按钮的命名方式,您可以使用

string buttonName = ((Button)sender).Name;

按钮是你的按钮类

然后解析这个字符串得到你名字中已经包含的数字...

例如

string lastChar = buttonName[buttonName.length - 1];

编辑如果您希望保持名称相同,则可以使用 switch 语句

string s;
switch(((Button)sender).Name)
{
case "btnLevelEasy":
s = "1";
break;
于 2013-01-30T07:46:48.970 回答