programatically highlight words using c#:

programatically highlight words using c#:

       Your output like this....

xaml:

    create a text block with name of tb.

 <TextBlock Height="auto" TextWrapping="WrapWidth="200" HorizontalAlignment="Left" Margin="45,12,0,0" Name="tb" Text="TextblockVerticalAlignment="Top" />

c# code:

         string source = "This is a example of Highlight a word using c#";   //Your source
        string[] highlight_words = { "example", "word" };                          //Your Key word

On your button click event call this function like this

         private void button1_Click(object sender, RoutedEventArgs e)
          {
            highilight(source);
           }

And copy paster this Function:

     public void highilight(string source)
        {
            int min = 0, chk = 0, chk2 = 0, tmp = 0;
            string negword = string.Empty; ;
            do
            {
                chk2 = 0;
                for (int j = 0; j < highlight_words.Count(); j++)     //find first negative keyword in source
                {
                    tmp = source.IndexOf(highlight_words[j]);
                    if (chk == 0 && tmp != -1)
                    { min = tmp; negword = highlight_words[j]; chk++; }
                    if (tmp < min && tmp != -1)
                    { min = tmp; negword = highlight_words[j]; }
                }

                var regex = new Regex(negword);
                var str = regex.Replace(source, "|", 1);          //replaces the first occurence
                var [] words = str.Split('|');

                tb.Inlines.Add(new Run() { Text = words[0], FontSize = 12, });         //split add it in a text block
                tb.Inlines.Add(new Run() { Text = negword, FontSize = 12, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.Orange) });
                source = words[1];
                tmp = 0; min = 0; chk = 0;


                for (int k = 0; k < highlight_words.Length; k++)     //check the negative keword is present or not
                {
                    if (source.IndexOf(highlight_words[k]) != -1)
                    { chk2++; }
                }

                if (chk2 == 0)
                { tb.Inlines.Add(new Run() { Text = source, FontSize = 12 }); }    //add the last part of substring

            } while (chk2 > 0);
        }

Comments

Popular posts from this blog

Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

Add content type to SharePoint List/Library using REST API

A type named 'SP.Data. could not be resolved by the model error