简体   繁体   English

如何将事件处理程序绑定到集合内部动态创建的控件?

[英]How to bind an Event Handler to a dynamically created control inside of a collection?

I'm working with C# again, and trying to catch up with some of the newer aspects, as the last time I worked with it LINQ didn't yet exist. 我再次使用C#,并试图赶上一些较新的方面,因为我上次使用LINQ时还不存在。 I am trying to create a calendar (not a date picker) in a Windows Store app, and dynamically create most of the controls. 我正在尝试在Windows Store应用程序中创建日历(而不是日期选择器),并动态创建大多数控件。 When a date is clicked/tapped, I want it to display information in a RichTextBlock. 当单击/点击一个日期时,我希望它在RichTextBlock中显示信息。 That part isn't the problem...I have a Grid control, and can iterate through the month to create the calendar by creating RichTextBlocks in a List called, naturally enough, calBlocks. 那不是问题……我有一个Grid控件,可以通过在一个称为calBlocks的List中创建RichTextBlocks来遍历月份来创建日历。 This is the part that is giving me fits: 这是给我适合的部分:

    for (int i = 0; i < DateTime.DaysInMonth(CurrentDate.Year, CurrentDate.Month); i++)
    {
        calBlocks.Add(new RichTextBlock());
        calBlocks[i].Tapped += new TappedEventHandler(calBlock_Clicked);
    }

I've defined a calBlock_Clicked handler, but it never seems to be reached. 我已经定义了一个calBlock_Clicked处理程序,但似乎从未达到过。 I seem to be missing something, and I think it's something pretty basic, but I just can't seem to see it. 我似乎缺少了一些东西,我认为这是非常基本的东西,但是我似乎看不到它。

If you're interested, this is the calBlock_Clicked handler. 如果您有兴趣,这是calBlock_Clicked处理程序。 It's pretty basic, and just for debugging purposes at the moment: 这是非常基本的,目前仅用于调试目的:

    void calBlock_Clicked(object sender, TappedRoutedEventArgs e)
    {

        Paragraph MainHeader = new Paragraph();
        Run HeaderDate = new Run();

        HeaderDate.Text = "This would be a long format date";

        MainHeader.Inlines.Add(HeaderDate);

        TestBlock.Blocks.Add(MainHeader);
    }

I have looked, but I haven't seen anything that answered exactly this...there have been a few similar posts, but nothing that quite answered my questions. 我已经看过了,但是还没有看到任何能完全回答这个问题的信息……有一些类似的帖子,但是没有什么可以完全回答我的问题。 If there already are, please point me to them! 如果已经存在,请指向我!

Set the IsTextSelectionEnabled property of your RichTextBlock to false upon construction. IsTextSelectionEnabled时将RichTextBlockIsTextSelectionEnabled属性设置为false

This will re-enable the Tapped event. 这将重新启用Tapped事件。

Example: 例:

calBlocks.Add(new RichTextBlock() { IsTextSelectionEnabled = false });

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

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