How to add xamarin native platform effect to all elements?

Yaser Moradi
2 min readNov 14, 2017

--

Native platform effect is a really handy feature of xamarin forms. Whenever you use Xaml tags such as <Entry> and <Button>, xamarin forms creates a native element to make it work on each platform. For example, there is an “android.widget.TextView” behind every “Label” in android.

Although you can change your Label’s UI using Xaml attributes such as Background, sometimes you need to do something with the native element itself.

For example, you might need to add “Clear button” to your “Entry” elements. You can use renderers to achieve the same goal, but Renderers are out there to accomplish big goals such as adding a new element from scratch.

To add “Clear button” to your “Entry”, first you need to search for it. I found this: https://stackoverflow.com/a/320079/2720104 for you (:

So, let’s create an effect for this using docs provided by Xamarin team.

((UITextField)Control).ClearButtonMode = UITextFieldViewMode.WhileEditing;

That’s a result which is cool (:

But, there is a problem here. Should I add that effect to all Entry tags I have in my app? It’s too bad!

<Entry>                                            	<Entry.Effects>                                                		<effects:EntryClearButtonEffect />
</Entry.Effects>
</Entry>

But there is a solution! You can create an Attached property and at that attached property, you can add your effect. Then you can define a global style for all your Entry tags in App.xaml. As a result, all your Entry tags will have a clear button.

You can continue using Entry as before, without adding effect to all of them manually!

Working sample codes can be found on github.com

Hope this helps you develop better apps with fewer codes from today (:

--

--