如何组合将值传递到一个的多个点击事件?

时间:2013-01-30 07:30:50

标签: c# xaml button windows-phone-8 windows-phone

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

    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));
    }

2 个答案:

答案 0 :(得分: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,你知道如何在每个按钮上链接事件吗? (在事件中只需单击下拉菜单并选择上一个创建的事件)

答案 1 :(得分:2)

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

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

按钮是您的按钮类

然后解析此字符串以获取您的名字中包含的数字......

例如

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

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

string s;
switch(((Button)sender).Name)
{
case "btnLevelEasy":
s = "1";
break;