0

I'm creating multiple Canvas in run time, and each Canvas has a TextBox as Children. These Canvas are Children of a WrapPanel. My code is as follow:

List<Canvas> cvList = new List<Canvas>();
WrapPanel wp = new WrapPanel();

// function (e.g. a Click event) to add a Canvas with a TextBox
Canvas cv = new Canvas();
TextBox tb = new TextBox();
cv.Children.Add(tb);
cvList.Add(cv);
wp.Children.Add(cv);

If after the function is processed 10 times and 10 Canvas is create, I need to change the Text of one specific UIElement (e.g. the 5th TextBox). How would I do so? There is no index to use like that in an array.

[Edit] If I have a button click event also generated in run-time, each button will close its corresponding Canvas:

List<Button> btnList = new List<Button>();

// function to add Canvas with a Button
Button btn = new Button();
btn.Content = "Destroy";
btn.Click += destroy_Click;
btnList.Add(btn);
cv.Children.Add(btn);

// Destroy click event
private void destroy_Click(object sender, RoutedEventArgs e)
{
if (sender == ????)
{}
}

What should I compare my sender to?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
KMC
  • 19,548
  • 58
  • 164
  • 253
  • "There is no index to use like that in an array." Yes, there is. List has an index *exactly* like array: `cvList[4]`. So does UIElementCollection (which is what Canvas.Children is): `cvList[4].Children[0]`. – itowlson Apr 04 '11 at 03:25

1 Answers1

2

As I was trying to explain in your last question (which you probably just should have updated) you don't need a separate list, just use the WrapPanel directly to access its children - You know you only added Canvas elements to your WrapPanel so you can cast appropriately:

TextBox textbox = (wp.Children[5] as Canvas).Children[0] as TextBox;
textbox.Text = "Hello";
Community
  • 1
  • 1
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • thanks, I though it will be more appropriate to separate the question. Also I edited my question to explain my problem I had with a click event of a UIElement in a List. – KMC Apr 04 '11 at 04:12