Created
October 13, 2018 13:42
-
-
Save LSViana/c4f9cacc1c59d438bd84e6350f3bddb3 to your computer and use it in GitHub Desktop.
Creating a simplified version of ConstraintExpression with Type=RelativeToView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using Xamarin.Forms; | |
using Xamarin.Forms.Internals; | |
using Xamarin.Forms.Xaml; | |
namespace Playground.Helpers | |
{ | |
[ContentProperty(nameof(Value))] | |
public class ToViewExtension : 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 != 4) | |
return null; | |
// Removing white spaces | |
for (int i = 0; i < values.Length; i++) | |
values[i] = values[i].Trim(); | |
// Getting values to define Constraint | |
var elementName = values[0]; | |
var property = values[1]; | |
if (!double.TryParse(values[2], out double constant)) | |
return null; | |
if (!double.TryParse(values[3], out double factor)) | |
return null; | |
// | |
IReferenceProvider service1 = serviceProvider.GetService<IReferenceProvider>(); | |
View byName; | |
if (service1 != null) | |
{ | |
byName = (View)service1.FindByName(elementName); | |
} | |
else | |
{ | |
IProvideValueTarget service2 = serviceProvider.GetService<IProvideValueTarget>(); | |
if (service2 == null || !(service2.TargetObject is INameScope)) | |
return (Constraint)null; | |
byName = ((INameScope) service2.TargetObject).FindByName(elementName) as View; | |
} | |
var pi = typeof(RelativeLayout).GetProperties() | |
.FirstOrDefault(a => a.Name == property.ToString() && a.CanRead); | |
return Constraint.RelativeToView(byName, (p, v) => (double)pi.GetValue(v) * 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