tags:

views:

243

answers:

1

I am trying to create an array of textblocks. And I am trying to create a new event for each textblock that is created. I have no problem creating the array of text blocks however I am not sure how to create a "list" of events to go along with it. Here is the code I have so far.

 List<TextBlock> myList = new List<TextBlock>();

 int octr = 1;

    public void createlabels()
    {

        TextBlock tb = new TextBlock();

        tb.Width = 200;
        tb.Height = 60;

        tb.Text = "label";

        Canvas.SetLeft(tb, octr + 100);
        Canvas.SetTop(tb, octr + 100);

        myList.Add(tb);

        myList[octr].MouseLeftButtonDown += new MouseButtonEventHandler(mylist_mouseleftbuttondown);

        octr++;
    }

    void mylist_mouseleftbuttondown(object sender, MouseButtonEventArgs e)
    {
        TextBlock tb = (TextBlock)sender;

         tb.Text = "New label";

    }
+2  A: 

is the event getting fired at all?

TextBlock tb = new TextBlock();
        tb.Width = 200;
        tb.Height = 60;

        tb.Text = "label";

        Canvas.SetLeft(tb, octr + 100);
        Canvas.SetTop(tb, octr + 100);

        tb.MouseLeftButtonDown += new MouseButtonEventHandler(mylist_mouseleftbuttondown);

        myList.Add(tb);

try this, i believe this must work.

Anirudh Goel
I can't see why his original code wouldn't work, but yours is the way I would do it.
Alastair Pitts
I too don't know why his didn't work, may be the list containing objects needs one more level of boxing?
Anirudh Goel
@Anirudh: You've indicated whats wrong with the orignal code in your comment to the question. The indexer is off by 1.
AnthonyWJones
I think that the reason the original code doesn't work is that the event is attached to a TextBlock with an index higher than the index of the textblock just added to the List. For example on the first execution of createlabels() you add a TextBlock to myList and it will occupy position 0. But you octr variable holds value 1 and therefore you attempt to attach event to a TextBlock that occupies position 1 in the List, which I think shouldn't even be there yet.
Przemek
I tried to shorten the amount of code I put into the example. Setting the index to a 1 was a typo on my part. I also tried initializing the new mousedownevent before I added it to the list and that didn't work either. I may have to try another approach. Thank you for taking the time to answer my question.
Weston Goodwin