4

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>

1 Answer 1

8

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 };
});
Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible that there are multiple TextCells in DataTemplate? In that case, how to bind the fields properly?
@user1 could you please show us how to have button and label on same DateTemplate ..thanks
@user1 hey if you have stacklayout instead of textcell and have two labels inside the stacklayout. How do you know which one you are binding withdt.SetBinding(Label.TextProperty, new Binding("b")) how to specify which label I want to bind to. Or even navigating into complex datatemplate such as Grid?
@Luminous_Dev in your case dt should be the Label you are going to set the binding on

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.