Articles in this section
Category / Section

How to programmatically search and highlight a text in WPF Edit Control?

1 min read

You can search the text programmatically in WPF EditControl by using FindText property and highlight the searched text by using SelectLines() method.

XAML

<Grid>
    <Grid.RowDefinitions>
         <RowDefinition Height="*"/>
         <RowDefinition Height="Auto"/>
     </Grid.RowDefinitions>
 
     <syncfusion:EditControl Name="Edit1" Background="White" Margin="0" Foreground="Black" ShowLineNumber="True" EnableIntellisense="False" />
     <Button Content="Get position of the highlighted text" Grid.Row="1" Click="Button_Click" Height="40" Width="200" />
</Grid>

C#

public MainWindow()
{
    InitializeComponent();
    Edit1.DocumentLanguage = Languages.CSharp;
    Edit1.DocumentSource = "../../Source.cs";
}
 
private void Button_Click(object sender, RoutedEventArgs e)
{
    //Getting the string to find the text
    Edit1.FindOptions.FindText = "BusinessObject";
 
   for (int i = 0; i < Edit1.Lines.Count; i++)
   {
      //Check whether Lines collection contains the required string
      if (Edit1.Lines[i].Text.Contains(Edit1.FindOptions.FindText))
      {
         string pat = @"" + Edit1.FindOptions.FindText;
         Regex r = new Regex(pat, RegexOptions.IgnoreCase);
         Match m = r.Match(Edit1.Lines[i].Text);
         //Get the string index and length
         Edit1.SelectLines(i, i, m.Index, m.Index + m.Length);
         MessageBox.Show("current position\n" + "Linenumber=" + Edit1.LineNumber + "\n cursorindex=" + m.Index);
      }
   }
}

Search and highlight a text in WPF EditControl

C#: View sample in GitHub

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied