'WPF How to find a specific control in an ItemsControl with data binding

I have an ItemsControl which is bound to a list:

<ItemsControl x:Name="icFiles" ItemsSource="{Binding Path=files}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <CheckBox Content="" IsChecked="{Binding IsChecked, Mode=TwoWay}" />
                <TextBlock x:Name="ThisTextBlock" Text="{Binding FileName}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
private readonly List<FileModel> files = new();

icFiles.ItemsSource = files;

I want to highlight certain text in the TextBlock in the ItemsControl. For this, I thought about using a TextPointer:

string? highlightText = "blue";

int highlightTextIndex = ThisTextBlock.Text.IndexOf(highlightText);
if(highlightTextIndex >= 0)
{
    TextPointer textStartPointer = ThisTextBlock.ContentStart.DocumentStart.GetInsertionPosition(LogicalDirection.Forward);
    TextRange? highlightTextRange = new TextRange(textStartPointer.GetPositionAtOffset(highlightTextIndex), textStartPointer.GetPositionAtOffset(highlightTextIndex + highlightText.Length));
                highlightTextRange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Blue);
    }
}

How do I find this ThisTextBlock?



Solution 1:[1]

First of all, you need to delete the Binding from code behind.

You can do this using Loaded event as follows:

 <ItemsControl x:Name="icFiles" ItemsSource="{Binding Path=files}">
     <ItemsControl.ItemTemplate>
         <DataTemplate>
             <StackPanel Orientation="Horizontal">
                 <CheckBox Content="" IsChecked="{Binding IsChecked, Mode=TwoWay}" />
                 <TextBlock Loaded="ThisTextBlock_OnLoaded" x:Name="ThisTextBlock" Text="{Binding FileName}" />
             </StackPanel>
         </DataTemplate>
     </ItemsControl.ItemTemplate>
 </ItemsControl>    
  

 private void ThisTextBlock_OnLoaded(object sender, RoutedEventArgs e)
 {
    if (sender is TextBlock tb)
    {
        string? highlightText = "blue";
        int highlightTextIndex = tb.Text.IndexOf(highlightText);
        if (highlightTextIndex >= 0)
        {
            TextPointer textStartPointer = tb.ContentStart.DocumentStart.GetInsertionPosition(LogicalDirection.Forward);
            TextRange? highlightTextRange = new TextRange(textStartPointer.GetPositionAtOffset(highlightTextIndex), textStartPointer.GetPositionAtOffset(highlightTextIndex + highlightText.Length));
            highlightTextRange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Blue);
        }
     }
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ohad Cohen