user8531441
user8531441

Reputation:

Why is element I declared in XAML unreachable from C# code?

This is my project structure

I declare ListView in XAML (MainPage.xaml):

<ListView x:Name="ShoppingListsLV"
              HorizontalOptions="CenterAndExpand"
              Margin="3"/>

And tried to access it from my code (MainPage.xaml.cs):

ShoppingListsLV.ItemsSource = new string[] { "test", "test 2"};

And I have an error:

CS0103: The name ShoppingListsLV does not exist in the current context

Upvotes: 1

Views: 84

Answers (3)

SergioAMG
SergioAMG

Reputation: 428

Check that you are writing your code after the call:

InitializeComponent();

Also, check that your view is referencing the right code-behind file:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="YourNamespace.MainPage">

Finally, try to close VS, then go and delete from your projects folders the following ones:

Android - bin

Android - obj

iOS - bin

iOS - obj

This action will clear completely your cache. After this is done, reopen your solution in VS and perform a clear, re-build operation. Your references should be working fine now.

Upvotes: 1

Ivan I
Ivan I

Reputation: 9990

Your code is right, if you see the errors you need to build the app, it should work and you won't see the error anymore.

Upvotes: 0

Wasif Mahmood Mustafa
Wasif Mahmood Mustafa

Reputation: 597

Change the page Custom Tool property to MSBuild:UpdateDesignTimeXaml where your list exists.

Upvotes: 0

Related Questions