Xamarin Form ListView Text Binding Not Working

Ken95Ken95 Member ✭✭

I'm new in Xamarin and currently developing an Xamarin Form app consist of ListView.
here is my code:

Vehicle.cs

public class Vehicle
    {
        public string Vehnum { get; set; }

    }

VehiclePage.xaml.cs

public VehiclePage ()
{
        InitializeComponent();

        Vehicles.ItemsSource = new List<Vehicle>
        {
            new Vehicle(){Vehnum = "abcd1234"},
            new Vehicle(){Vehnum = "xyzv1236"},
            new Vehicle(){Vehnum = "qwer6523"},
        };


    }

VehiclePage.xaml

<ListView x:Name="Vehicles">
        <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.View>
                                <StackLayout>
                                    <Label Text="{Binding Vehnum}"/>
                                </StackLayout>

                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

However, when the app is running, the listview show the numbers of row correctly but without text. What could be the problem?

Tagged:

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    Looks like your Vehicle class doesn't derive from BindableObject or implement INotifyPropertyChanged... So there is no notification being raised to let your UI know to update.

    This tutorial should help fill in the blanks for MVVM binding
    http://redpillxamarin.com/2018/03/12/2018-101-vs2017-new-solution/

  • NMackayNMackay GBInsider, University mod
    edited November 2018

    @Ken95

    Actually that will not work work out of the box, you have to give your page an x:Name attribute and use relativesource binding to accomplish this.

    Give the page a name

    x:Name="MyPage"
    
    Listview Itemsource="{Binding Source={x:Reference MyPage}, Path=Vehicles}"
    
        <ViewCell>
                <StackLayout>
                     <Label Text="{Binding Vehnum}" />/>
                 </StackLayout>
            </ViewCell>
    

    Binding to code behind for this purpose is the wrong path to take though, really binding to the page control should be for a reusable page/control. Code behind eventually leads to re-engineering for the MVVM pattern, not using the MVVM pattern is fighting the goodness of the Forms framework.

  • Ken95Ken95 Member ✭✭

    Im not sure what really happened, I try to create another projects and use the same code, and it works.
    But still thanks for your answer @NMackay @ClintStLaurent

Sign In or Register to comment.