Home > OS >  Assigning values to children of a control
Assigning values to children of a control

Time:12-30

I want to assign text to the textbox in the stackpanel. There will be 20 or 25 textbox in total. My code can only assign a value to the first item.

XAML

<StackPanel x:Name="Products">
    <TextBox Height="35" FontSize="18"/>
    <TextBox Height="35" FontSize="18"/>
    <TextBox Height="35" FontSize="18"/>
    <TextBox Height="35" FontSize="18"/>
    <TextBox Height="35" FontSize="18"/>
    <TextBox Height="35" FontSize="18"/>
    <TextBox Height="35" FontSize="18"/>
    <TextBox Height="35" FontSize="18"/>
    <TextBox Height="35" FontSize="18"/>
    <TextBox Height="35" FontSize="18"/>
</StackPanel>

CODE

foreach (Control control in Products.Children) // Ürünler listeleniyor
{
    if (control.GetType() == typeof(TextBox))
    {
        ((TextBox)control).Text = "messages";
    }
}

CodePudding user response:

First you need to define your starting point in your example the stackpanel named "Products":

Control products = (Control)Root.FindName("Products");

Secondly you can use VisualTreeHelper to run through all of its child controls which are textboxes and change their text:

int nChildCount = VisualTreeHelper.GetChildrenCount(products );
for (int i = 0; i <= nChildCount - 1; i  ){
   Visual v = (Visual)VisualTreeHelper.GetChild(products , i);
   if (v.GetType() == typeof(TextBox)){
      v.text="my new text";
   }
}

CodePudding user response:

for (int i = 0; i < Products.Children.Count; i  )
{
      var child = VisualTreeHelper.GetChild(Products, i);
      if (child.GetType() == typeof(TextBox))
      {
           ((TextBox)child).Text = i   "messages";
      }                
}

it worked this way.

  • Related