0

My question seems to be simple and I hope it is.
I have a dynamic collection of TextBox in a UiElementCollection.
The TextBox are children of a StackPanel.

My goal is simple :
Create a new TextBox with the Text of for example UiElementCollection[1].

TextBox myTextBox = new TextBox();                        // New TextBox
UiElementCollection myCollection = myStackPanel.Children; // New Collection

// If I call this :
myCollection[8] = myTextBox; 
// Error when I call my method
// --> System.ArgumentException

// If I call this  :
myTextBox = myCollection[8];
// Error in my code
// --> Cannot convert.. UiElement to Controls.TextBox

string myString = myTextBox.Text;

Any one can help me to handle this please ? Thanks.

C0ZEN
  • 894
  • 11
  • 41

1 Answers1

3

You have to cast it first, there is no implicit conversion:

myTextBox = (TextBox)myCollection[8];

Of course, it is likely a good idea to check if that was a TextBox first using is, or do a null check and as.

Also, the standard note for WPF applies here, in general you should be accessing such data through bindings, not direct UI manipulation.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117