Adding Effects in Xamarin Forms

In Mobile Development by Christian HissibiniLeave a Comment

Effects allow the changing of platform specific properties on a native control without the need for a Custom Renderer. They are typically used for changing styling of a property when the property has not been exposed via the Xamarin Forms Control.

  • Effects are designed to be reusable
  • Need a custom renderer if you want to override methods
  • Need a custom renderer if you want to replace the control used on the platform

Documentation: Introduction to Effects

Example Use Case: Changing the color of the placeholder text in an Entry control.

First on the native platform, in this example iOS, we create a Platform Effect.

[assembly:ResolutionGroupName ("Xamarin")]
[assembly:ExportEffect (typeof(PlaceholderEffect), "PlaceholderEffect")]
namespace Mobile.iOS
{
    public class PlaceholderEffect : PlatformEffect<UIView, UITextField>
    {
        protected override void OnAttached()
        {
            Control.AttributedPlaceholder = new NSAttributedString(Control.Placeholder, null, UIColor.Red);
        }

        protected override void OnDetached()
        {
        }

        protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
        {
            base.OnElementPropertyChanged(args);
            // You can do effects only when certain properties change here.
        }
    }
}

Next if we are in a PCL we need to add a RoutingEffect so XAML in the PCL can reference the platform specific implementation.

public class PlaceholderEffect : RoutingEffect
{
    public PlaceholderEffect () : base ("Xamarin.PlaceholderEffect")
    {
    }
}

Now we can add the effect to the control.

// Add this to your page attributes (change Mobile.Effects to whatever full namespace your placeholder effect is in)
xmlns:local="clr-namespace:Mobile.Effects"

<Entry Text="{Binding EntryField}">
    <Entry.Effects>
        <local:PlaceholderEffect />
    </Entry.Effects>
</Entry>

Ref
https://docs.microsoft.com – https://xamarinhelp.com – https://blog.xamarin.com/

Leave a Comment