Reputation: 524
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
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
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
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