简体   繁体   中英

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. I am trying to create a calendar (not a date picker) in a Windows Store app, and dynamically create most of the controls. When a date is clicked/tapped, I want it to display information in a 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. 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. 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. 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.

This will re-enable the Tapped event.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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