# Effects
Effects simplifies platform specific customizations. When there is a need to modify a Xamarin Forms Control's properties, Effects can be used. When there is a need to override the Xamarin Forms Control's methods, Custom renderers can be used
# Adding platform specific Effect for an Entry control
- Create a new Xamarin Forms app using PCL File -> New Solution -> Multiplatform App -> Xamarin Forms -> Forms App; Name the project as
EffectsDemo
- Under the iOS project, add a new
Effect
class that inherits fromPlatformEffect
class and overrides the methodsOnAttached
,OnDetached
andOnElementPropertyChanged
Notice the two attributesResolutionGroupName
andExportEffect
, these are required for consuming this effect from the PCL/shared project.
using System;
using EffectsDemo.iOS;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ResolutionGroupName("xhackers")]
[assembly: ExportEffect(typeof(FocusEffect), "FocusEffect")]
namespace EffectsDemo.iOS
{
public class FocusEffect : PlatformEffect
{
public FocusEffect()
{
}
UIColor backgroundColor;
protected override void OnAttached()
{
try
{
Control.BackgroundColor = backgroundColor = UIColor.Red;
}
catch (Exception ex)
{
Console.WriteLine("Cannot set attacked property" + ex.Message);
}
}
protected override void OnDetached()
{
throw new NotImplementedException();
}
protected override void OnElementPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
try
{
if (args.PropertyName == "IsFocused")
{
if (Control.BackgroundColor == backgroundColor)
{
Control.BackgroundColor = UIColor.Blue;
}
else
{
Control.BackgroundColor = backgroundColor;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property " + ex.Message);
}
}
} }
using Xamarin.Forms;
namespace EffectsDemo
{
public class FocusEffect : RoutingEffect
{
public FocusEffect() : base("xhackers.FocusEffect")
{
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:EffectsDemo" x:Class="EffectsDemo.EffectsDemoPage">
<StackLayout Orientation="Horizontal" HorizontalOptions="Center" VerticalOptions="Center">
<Label Text="Effects Demo" HorizontalOptions="StartAndExpand" VerticalOptions="Center" ></Label>
<Entry Text="Controlled by effects" HorizontalOptions="FillAndExpand" VerticalOptions="Center">
<Entry.Effects>
<local:FocusEffect>
</local:FocusEffect>
</Entry.Effects>
</Entry>
</StackLayout>
</ContentPage>
Since the Effect was implemented only in iOS version, when the app runs in iOS Simulator
upon focusing the Entry
background color changes and nothing happens in Android Emulator
as the Effect
wasn't created under Droid
project