Xamarin forms listView fill without binding

aybkekaraarslanaybkekaraarslan USMember ✭✭
edited August 2016 in Xamarin.Forms

Hello
I have a listView;

`
ListView listView = new ListView();
Content = new StackLayout
{
Children = {
listView

}
}

    listView.ItemTemplate = new DataTemplate(() => new CustomCells());
    List<MyModel> myModels = new List<MyModel>();
    myModels.Add(new MyModel("Chris", 29, "Teen");
    myModels.Add(new MyModel("Anna", 56, "Elder");

    listView.ItemsSource = myModels;`

MyModel.cs
public class MyModel{ public MyModel(string name, int age, string type) { this.name = name; this.age = age; this.type = type; } public string name {get; set;} public int age {get; set;} public string type {get; set;} } }

CustomCell.cs
public class CustomCell : ViewCell { Label name = new Label{ Text = "{Binding name}" } int age = "{Binding age}"; (???????????????????) }

How can I get age from MyModel class? I couldn't find any solution about this. I wanna reach MyModel values like a field;
Label name = new Label { Text = MyModel.name }

How will it be possible?

Answers

  • MichaelRumplerMichaelRumpler ATMember ✭✭✭✭✭

    "{Binding name}" only works in Xaml. In code this is much more complicated. This should do the trick:

    Label name = new Label();
    name.SetBinding(Label.TextProperty, nameof(MyModel.name));
    

    To get the age without binding you have to do this in CustomCell:

        protected override void OnBindingContextChanged()
        {
            base.OnBindingContextChanged();
    
            var vm = (MyModel)BindingContext;
            int age = vm.age;
        }
    
  • aybkekaraarslanaybkekaraarslan USMember ✭✭

    name.SetBinding(Label.TextProperty, nameof(MyModel.name)); only get field name.
    When I run the project label text will be "name". I dont't want to this. I wanna get name value for all listview items.
    @MichaelRumpler

Sign In or Register to comment.