【问题标题】:Dynamically created elements' event handler动态创建元素的事件处理程序
【发布时间】:2014-04-25 13:25:57
【问题描述】:

我正在开发一个 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);
    }

whanTapped 事件处理程序:

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

调试时,“object sender”提供了足够的信息来识别 sender - TextBlock 的“Text”属性,但在编码期间,我从“object sender”得到的只有以下内容:Equals、GetHashCode、GetType、ToString。 (ToString 只告诉这一般是一个TextBlock,仅此而已)。

【问题讨论】:

    标签: c# windows-phone-8 event-handling windows-phone windows-phone-7.1


    【解决方案1】:

    但在编码过程中,我从“对象发送者”得到的只是以下内容:
    等于、GetHashCode、GetType、ToString。

    因为Object 只支持那些方法并且它是所有(几乎)的父类。 父类可以包含/保存子类成员,但除非您将它们转换为子类型,否则您无法访问子成员。

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

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

    【讨论】:

    • 谢谢,工作 =) 将在 10 分钟内标记为正确答案(说我还不能)
    • @IgnasLaukineitis:这都是我的特权。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 2019-04-13
    • 2012-09-23
    • 2016-01-28
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多