Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin ListView with Binding in xaml to C# code

How do I convert the following ListView with ItemTemplate and Binding in the xaml file to equivalent C# code:

<ListView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" 
    ItemsSource="{Binding A}" ItemSelected="OnClick">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding b}" Detail="{Binding c}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
like image 334
Jon Avatar asked Feb 10 '23 06:02

Jon


1 Answers

Try something like this:

ListView lv = new ListView();
lv.HorizontalOptions = LayoutOptions.FillAndExpand;
lv.VerticalOptions = LayoutOptions.FillAndExpand;
lv.SetBinding(ListView.ItemsSourceProperty, new Binding("A"));
lv.ItemSelected += (sender, args) =>
{
    onclick(sender, args);
}; //Remember to remove this event handler on dispoing of the page;
DataTemplate dt = new DataTemplate(typeof(TextCell));
dt.SetBinding(TextCell.TextProperty, new Binding("b"));
dt.SetBinding(TextCell.DetailProperty, new Binding("c"));
lv.ItemTemplate = dt;

For more complex Datatemplates do:

DataTemplate dt = new DataTemplate(() => 
{
   var button = new Button();
   button.SetBinding(Button.TextProperty, new Binding("Name"));
   return new ViewCell { View = button };
});
like image 51
User1 Avatar answered Feb 12 '23 10:02

User1