Search code examples
c#xamlxamarinxamarin.formsbindableproperty

BindableProperty (List<>) in Xamarin Forms


my problem is the following: I have my ContentPage which has a ResourceDictionary with some DataTemplates. One of the templates takes the Horse Object (which holds the List<Weight>'s). I display several stats of that object but when I want to pass variables from the Horse Object to another view such as the following:

<graph:LineGraph x:Name="displayWeight" WeightOfHorse="{Binding Weight}"/>

Code Behind WeightOfHorse:

public static readonly BindableProperty WeightOfHorseProperty = BindableProperty.Create(
    nameof(WeightOfHorse),
    typeof(IList<Weight>),
    typeof(LineGraph),
    defaultBindingMode: BindingMode.TwoWay);

public IList<Weight> WeightOfHorse
{
    get => (IList<Weight>)GetValue(WeightOfHorseProperty);
    set => SetValue(WeightOfHorseProperty, value);
}

I just don't manage to pass the values, I know that they are available because I can display them in a simple Collectionview.

What am I doing wrong?


Solution

  • I figured it out, this works. It seems that you need to assign the property by the changing event.

    public static readonly BindableProperty WeightOfHorseProperty = BindableProperty.Create(
    nameof(WeightOfHorse),
    typeof(IEnumerable<Weight>),
    typeof(LineGraph),
    defaultBindingMode: BindingMode.TwoWay,
    propertyChanged: OnEventNameChanged);
    
    public IEnumerable<Weight> WeightOfHorse
    {
    get => (IEnumerable<Weight>)GetValue(WeightOfHorseProperty);
    set => SetValue(WeightOfHorseProperty, value);
    }
    
    static void OnEventNameChanged(BindableObject bindable, object oldValue, object newValue)
    {
    var control = (LineGraph)bindable;
    control.WeightOfHorse = (List<Weight>)newValue;
    ...
    }