Skip to content

Instantly share code, notes, and snippets.

@LSViana
Created October 13, 2018 13:42
Show Gist options
  • Save LSViana/8ec3ca4068065c23b2f0a0d5ced79db5 to your computer and use it in GitHub Desktop.
Save LSViana/8ec3ca4068065c23b2f0a0d5ced79db5 to your computer and use it in GitHub Desktop.
Creating a simplified version of ConstraintExpression with Type=RelativeToParent
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Playground.Helpers
{
[ContentProperty(nameof(Value))]
public class ToParentExtension : IMarkupExtension<Constraint>
{
public String Value { get; set; }
public Constraint ProvideValue(IServiceProvider serviceProvider)
{
if (Value is null)
return null;
var values = Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (values.Length != 3)
return null;
// Removing white spaces
for (int i = 0; i < values.Length; i++)
values[i] = values[i].Trim();
// Getting values to define Constraint
var property = values[0];
if (!double.TryParse(values[1], out double constant))
return null;
if (!double.TryParse(values[2], out double factor))
return null;
//
var pi = typeof(RelativeLayout).GetProperties()
.FirstOrDefault(a => a.Name == property.ToString() && a.CanRead);
return Constraint.RelativeToParent(p => (double)pi.GetValue(p) * factor + constant);
}
object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
{
return ProvideValue(serviceProvider);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment