简体   繁体   English

动态创建元素的事件处理程序

[英]Dynamically created elements' event handler

I'm working on a Windows Phone 7.1 (7.5) app. 我正在开发Windows Phone 7.1(7.5)应用程序。 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. 想法:app从服务器获取数据列表,为每个数据创建一个TextBlock,并为每个数据应用Tap事件处理程序。 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) 用于创建新TextBlock的部分:(注意:itemsAdded是一个外部变量,即设置适当的边距)

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: whanTapped事件处理程序:

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. 在调试时,“对象发送者”提供了足够的信息来识别发送者 - TextBlock的“Text”属性,但在编码期间,我从“对象发送者”获得的是以下内容:Equals,GetHashCode,GetType,ToString。 (ToString only tells that this is generally a TextBlock, that's all). (ToString只告诉它通常是一个TextBlock,就是全部)。

but during coding, all i get from "object sender" is the following: 但在编码过程中,我从“对象发送者”获得的是以下内容:
Equals, GetHashCode,GetType, ToString. Equals,GetHashCode,GetType,ToString。

because Object only supports those methods and it is the parent class of all (almost). 因为Object只支持那些方法,它是所有(几乎)的父类。 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. 和父类可以包含/保持子类memebrs,但除非将它们转换为子类型,否则不能访问子成员。

so you use can sender object but you need to cast it to your control TextBlock to get the required members to invoke. 因此,您使用can sender对象,但需要将其TextBlock转换为控件TextBlock以获取所需的成员调用。

TextBlock temp = (TextBlock) sender;
temp.Invi=okeSomething(); //now you can invoke `TextBlock` memebrs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM