Press "Enter" to skip to content

Hashtags detection in Xamarin Forms

Recently, I helped a friend by implementing a feature that detects hashtags and handles when users tap on them. After doing some research got inspired by this nice post https://xamarinhelp.com/hyperlink-in-xamarin-forms-label/.

At first, I was planning on using a converter to style the tags and behavior to handle when the user taps on them. But then realized I could actually do both by using just a behavior. So here is how I did it:

Let’s start! 

1. Regex to detect hashtags

Used this regex to detect the hashtags: @"(?<=#)\w+"

2. Create a behavior

Defined a bindable command property in the behavior so that it’s triggered when the user taps on a hashtag. Also added a property to set the hashtag text color.

When formatted text changes I get the string value and clear the spans. After that, I identify the hashtags by using the regex mentioned above. Then add a span to the label FormattedText property for each text part, when it’s hashtag you can style it differently (For this sample, I just changed the color) and add tap gesture recognizer so that we can handle when users tap on each hashtag. We do this by associating the behavior command to each tap gesture recognizer.

3. Use the behavior

Now, we can add the behavior to a Label and bind to the command. Should use FormattedText property to set the Text since that’s the one we are checking on the Behavior.

This is the result:

You can check the full source code here.

Happy hashtags!