Question

I'm working on a Windows Phone 7.1 (7.5) app. The idea: app gets an list of data from server, creates a TextBlock for each of them and applies Tap event handler for each of them. The problem: since I can only use one handler for all of the elements, how to identify the sender?

The part for creating a new TextBlock: (note: itemsAdded is an outside variable, that is to set proper margins)

void addInfoItem(string text)
    {
        Thickness tempThick = fatherText.Margin;
        tempThick.Top += itemsAdded * 58;
        itemsAdded++;
        TextBlock temp = new TextBlock() { Text = text, FontSize = 40, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Margin = tempThick };
        temp.Tap += whenTapped;
        ContentPanel.Children.Add(temp);
    }

whanTapped event handler:

private void whenTapped(object sender, RoutedEventArgs e)
    {
        //how to identify the sender?
    }

When debugging, "object sender" gives enough info to identify the sender - "Text" property of the TextBlock, but during coding, all i get from "object sender" is the following: Equals, GetHashCode, GetType, ToString. (ToString only tells that this is generally a TextBlock, that's all).

Was it helpful?

Solution

but during coding, all i get from "object sender" is the following:
Equals, GetHashCode,GetType, ToString.

because Object only supports those methods and it is the parent class of all (almost). and parent class can contain/hold the child class memebrs but you can't access the child members untill unless you cast them to the child type.

so you use can sender object but you need to cast it to your control TextBlock to get the required members to invoke.

TextBlock temp = (TextBlock) sender;
temp.Invi=okeSomething(); //now you can invoke `TextBlock` memebrs
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top