samedi 29 avril 2017

Xamarin.Forms access Binding object data

I want to make a label that will extract the name or some other data of the bound item.

[Display(Description = "Gimme your goddamm first name will ya")]
public string FirstName { get; set; }

Code:

public class TitleLabel : ContentView
{
  public Label Label { get; } = new Label();
  public TitleLabel()
  {
    //TODO ensure Content is not accessed manually
    Content = Label;
  }
  protected override void OnBindingContextChanged() =>
    Label.Text = GetPropertyTitle();


  string GetPropertyTitle()
  {
    var bcp = BindingContextProperty;

    //pseudo:
    var binding = GetBinding(bcp);
    var obj = binding.Object;
    var propertyName = binding.Path;
    var propertyInfo = obj.GetType().GetTypeInfo().DeclaredMembers
      .SingleOrDefault(m => m.Name == propertyName);
    if (propertyInfo == null)
      throw new InvalidOperationException();

    return propertyInfo.GetCustomAttribute<DisplayAttribute>().Description;
  }
}

XAML:

<my:TitleLabel Text="{Binding FirstName}" />

Rendered result:

<my:TitleLabel Text="Gimme your goddamm first name will ya" />





Aucun commentaire:

Enregistrer un commentaire