-1

I have a ObservableCollection binding in ItemsControl. In this ItemsControl is created some TextBoxes, one for each object in ObservableCollection.

Now I need to select text and highlight it depending the selected object but I'm not able to do it.

My xaml:

<StackPanel x:Name="stackPanel">
    <StackPanel.Children>
        <ItemsControl x:Name="itemsControl" ItemsSource="{Binding MyCollection}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding MyContent}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel.Children>
</StackPanel>

And this is my code which is called by one event:

for (int i = 0; i < this.stackPanel.Children.Count; i++)
{
    TextBox t = this.stackPanel.Children[i] as TextBox;
    if (t != null)
    {
        // do selection
    }
}

// and also in this way:
for (int i = 0; i < itemsControl.Items.Count; i++)
{
    UIElement uiElement =
       (UIElement)itemsControl.ItemContainerGenerator.ContainerFromIndex(i);

    TextBox t2 = (uiElement as TextBox);
    if (t2 != null)
    {
        // do selection
    }
}

How can I get these textbox? Thanks.

SirCris85
  • 9
  • 2
  • Possible duplicate of [MVVM and the TextBox's SelectedText property](https://stackoverflow.com/questions/2245928/mvvm-and-the-textboxs-selectedtext-property) – Bizhan Jun 19 '18 at 15:30
  • My advice is try to avoid manipulate directly the UI, bind them to an object and modify the object instead – Tony Jun 19 '18 at 15:47
  • It isn't exactly what I need but gives me an idea to resolve it. Thanks – SirCris85 Jun 25 '18 at 18:51

1 Answers1

0

The following code selects one text box at index i:

ContentPresenter c = (ContentPresenter)itemsControl.ItemContainerGenerator.ContainerFromIndex(i);
TextBox t2 = c.ContentTemplate.FindName("textboxName", c) as TextBox;

if (t2 != null)
{
    t2.Focus();
    t2.SelectAll();
}

You have to name your text box in xaml:

<TextBox x:Name="textboxName" ....

Note that, You cannot focus more than 1 element at a time, so highlighting all elements is not possible this way. You have to change highlighted text color manually (via binding or code)

Bizhan
  • 16,157
  • 9
  • 63
  • 101