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="Wrap" Width="200" HorizontalAlignment="Left" Margin="45,12,0,0" Name="tb" Text="Textblock" VerticalAlignment="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
Post a Comment