This is my ItemsControl in the XAML file:
<ItemsControl x:Name="PNItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<TextBox Text="{Binding TextBoxText}" Width="150"/>
<Button Content="Remove" Width="50"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
The number of Textboxes I generate varies. I want to grab the text with this code:
string[] phoneNumbers = "";
foreach(TextBox tb in PNItemsControl.Items.OfType<TextBox>())
{
phoneNumbers.Append(tb.Text);
}
c.PhoneNumbers = phoneNumbers;
But the ItemsControl does not see the textboxes generated. I even tried to grab the buttons or the stackpanels and still the variable (tb in this case stays null). Did I make a mistake or is there an alternative to grab items from ItemsControl?
You should loop through PNItemsControl.Children
which are of type FrameworkElement
!
So:
foreach(FrameworkElement in PNItemsControl.Children)
or
foreach (var element in PNItemsControl.Children.OfType<FrameworkElement>())
from there you should be able to identify your textboxes