KMC
KMC

Reputation: 20036

Access to UIElement.Properties in a List<UIElement>

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?

Upvotes: 0

Views: 422

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160962

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";

Upvotes: 2

Related Questions