Hi there,
I'm trying to create a CarouselPage in Xamarin.Forms using XAML.
This CarousePage is populated by an ItemSource.
The problem is that when I try to read a label.Text in CS from a XAML page, I've an error saying "the name 'xyz' does not exist in the current context".
I think it's caused by a namespace error but I don't know how to resolve it.
Can you help me?
This is the XAML code:
MainPage.xaml
<?xml version="1.0" encoding="UTF-8"?> <CarouselPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:control="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView" x:Class="CarouselPageNavigation.MainPage"> <CarouselPage.ItemTemplate> <DataTemplate> <ContentPage> <ContentPage.Padding> <OnPlatform x:TypeArguments="Thickness" iOS="0,40,0,0" Android="10,0,10,0" /> </ContentPage.Padding> <StackLayout> <Label x:Name="lblName" Text="{Binding Name}" FontSize="Medium" /> </StackLayout> </ContentPage> </DataTemplate> </CarouselPage.ItemTemplate> </CarouselPage>
and this is the code behind
MainPage.xaml.cs
using System; using Xamarin.Forms; namespace CarouselPageNavigation { public partial class MainPage : CarouselPage { public MainPage() { InitializeComponent(); ItemsSource = ProductsDataModel.All; lblName.Text = "test"; // **<== HERE THE ERROR** } } }
Answers
You should set the Name property that your Label's Text binds to rather than trying to set the Label's Text property. As the Label is within an ItemTemplate it won't be accessible in the way you intend.
Are you trying to parse the x:Name in the Binding place?
This is not how you define the text. The binding refers to a binding to the viewmodel or any other bindingcontext you have added to the page.
for example:
I have set a BindingContext to a viewmodel which I wrote with certain data in it. I have for example bound my listview Itemsource
I have declared a collection inside my SettingViewModelPage that is of name ''MenuList'' for example:
SettingsViewModelPage
If I were you I should read up about DataBinding and MVVM. You can watch alot of youtube tutorials for explaining this.
Cheers,
Luuk
@PaulDiston how can I set the Name property that my Label's Text binds to. Can you give me an example?