Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Setting ItemsSource for ListView defined in XAML throws InvalidCastException at runtime

$
0
0

I am seeing some strange behavior with the ListView control when I create the ListView in Xaml

If I define a ListView in Xaml

            <ListView x:Name="listView" VerticalOptions="FillAndExpand">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Label Text="{Binding Title}" />
                        <!--<ImageCell Text="{Binding Title}" ImageSource="{Binding IconSource}" />-->
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

and then in code set the ItemsSource

         var masterPageItems = MasterPageItems = new ObservableCollection<MasterPageItem>()
        {
            new MasterPageItem
            {
                Title = "Map",
                TargetType = typeof (MapPage)
            },
            new MasterPageItem
            {
                Title = "Start Survey",
                TargetType = typeof (StartPage)
            },
            new MasterPageItem
            {
                Title = "About",
                TargetType = typeof (AboutPage)
            }
        };  

        listView.ItemsSource = masterPageItems; 

When I run the application crashes and I will get: a message box System.InvalidCastException: Specified cast is not valid.

However if I create the ListView in code it works just fine.

           ListView list = new ListView
            {
                ItemsSource = masterPageItems
            };

Any ideas what is going on here? I would much rather be doing this in Xaml

Thanks
-Joe


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>