Hi,
I'am trying to achieve an gradient background effect for layout controls. On a grid control it works like a charm. But on a Frame the OnAttached handler is not executed allthough the effect has been attached.
Thanks in advance.
public class BackgroundGradientEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
this.UpdateGradient();
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
if (args.PropertyName == GradientEffect.StartColorProperty.PropertyName || args.PropertyName == GradientEffect.EndColorProperty.PropertyName)
{
this.UpdateGradient();
}
}
private void UpdateGradient()
{
Color startColor = GradientEffect.GetStartColor(this.Element);
Color endColor = GradientEffect.GetEndColor(this.Element);
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TopBottom, new []{ startColor.ToAndroid().ToArgb(), endColor.ToAndroid().ToArgb()});
Container.Background = gradientDrawable;
}
protected override void OnDetached()
{
}
}
public static class GradientEffect
{
public static readonly BindableProperty HasGradientProperty =
BindableProperty.CreateAttached("HasGradient", typeof(bool), typeof(GradientEffect), false, propertyChanged: OnHasGradientChanged);
public static readonly BindableProperty StartColorProperty = BindableProperty.CreateAttached("StartColor", typeof(Color), typeof(GradientEffect), Color.Default);
public static readonly BindableProperty EndColorProperty = BindableProperty.CreateAttached("EndColor", typeof(Color), typeof(GradientEffect), Color.Default);
private static void OnHasGradientChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as View;
if (view == null)
return;
var hasGradient = (bool)newValue;
if (hasGradient)
{
view.Effects.Add(new BackgroundGradientEffect());
}
else
{
var toRemove = view.Effects.FirstOrDefault(e => e is BackgroundGradientEffect);
if (toRemove != null)
view.Effects.Remove(toRemove);
}
}
public static Color GetStartColor(BindableObject view)
{
return (Color)view.GetValue(StartColorProperty);
}
public static void SetStartColor(BindableObject view, Color value)
{
view.SetValue(StartColorProperty, value);
}
public static Color GetEndColor(BindableObject view)
{
return (Color)view.GetValue(EndColorProperty);
}
public static void SetEndColor(BindableObject view, Color value)
{
view.SetValue(EndColorProperty, value);
}
}
public class BackgroundGradientEffect : RoutingEffect
{
public BackgroundGradientEffect() : base("Blub.BackgroundGradientEffect")
{
}
}
Regards