Rez
Rez

Reputation: 524

How to pass extra parameter to Tapped Event?

I create 10 TextBlock programmatically in Windows phone app 8.1
Now i want to add Tapped event to each TextBlock and pass extra parameter to it so i can find which TextBlock is tapped

I uses this code to create TextBlock with Tapped event:

for (int i=1;i<11;i++)
{
    TextBlock txtName = new TextBlock();
    txtName.Tapped += TxtName_Tapped;
}

private void TxtName_Tapped(object sender, TappedRoutedEventArgs e)
{
    // Something
}

How can i pass extra parameter?

Upvotes: 1

Views: 613

Answers (3)

M. Pipal
M. Pipal

Reputation: 734

In my opinion, very easy solution is to use Tag property:

for (int i=1;i<11;i++)
{
    TextBlock txtName = new TextBlock();
    txtName.Tag = i;
    txtName.Tapped += TxtName_Tapped;
}

and:

private void TxtName_Tapped(object sender, TappedRoutedEventArgs e)
{
    int tag = ((TextBlock)sender).Tag;
    //do something
}

Upvotes: 0

deeiip
deeiip

Reputation: 3379

As @Ric suggested you can always do:

 private void TxtName_Tapped(object sender, TappedRoutedEventArgs e)
    {
        clickedElementName = ((TextBlock)sender).Name ;
        if(clickedElementName == "element1")
        {
        }
    }

Upvotes: 2

daryal
daryal

Reputation: 14929

Instead of sending an extra parameter, you can use the sender parameter to identify the TextBlock.

for (int i=1;i<11;i++)
{
    TextBlock txtName = new TextBlock();
    txtName.Name = i.ToString();
    txtName.Tapped += TxtName_Tapped;
}

private void TxtName_Tapped(object sender, TappedRoutedEventArgs e)
{
    TextBlock textBlock = sender as TextBlock;
    switch(textBlock.Name)
    {    
         // list possible cases
         case "1":
         {
             // do something 
         }
    }
}

maybe you don't even need a switch statement as I do not know the exact requirement.

Upvotes: 0

Related Questions