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

本文关键字:事件处理 程序 创建 元素 动态 | 更新日期: 2023-09-27 18:00:02

我正在开发Windows Phone 7.1(7.5)应用程序。这个想法是:应用程序从服务器获取一个数据列表,为每个数据创建一个TextBlock,并为每个数据应用Tap事件处理程序。问题是:由于我只能对所有元素使用一个处理程序,如何识别发送者?

创建新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);
    }

whanTaped事件处理程序:

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

在调试时,"object sender"提供了足够的信息来识别TextBlock的sender-"Text"属性,但在编码过程中,我从"object senders"获得的信息如下:Equals、GetHashCode、GetType、ToString。(仅ToString告诉这通常是一个TextBlock,仅此而已)。

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

但在编码过程中,我从"object sender"得到的只是以下内容:
Equals、GetHashCode、GetType、ToString。

因为CCD_ 1只支持这些方法,并且它是所有方法(几乎)的父类。父类可以包含/保持子类memebr,但除非将其强制转换为子类型,否则不能访问子成员。

因此,您使用can sender对象,但需要将其强制转换为控件TextBlock,以获得要调用的所需成员。

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