Xamarin.Forms accessing controls written in markup from Code
Solution 1
To access a Forms control in the code-behind, you need to assign it a name, using the x:Name
attribute
in XAML:
<ListView HorizontalOptions="Center" x:Name="MyList" />
in code:
MyList.ItemsSource = myData;
Solution 2
There is a bug in Xamarin where VS doesn't see the defined x:Name http://forums.xamarin.com/discussion/25409/problem-with-xaml-x-name-and-access-from-code-behind
Say you've defined an image in XAML:
<Image x:Name="myImageXName" />
Then this should work in code behind:
this.FindByName<Image>("myImageXName");
Solution 3
In my case the problem was lack of line XamlCompilation(XamlCompilationOptions.Compile)]
in .xaml.cs file.
Example:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new MainPageViewModel();
}
...
}
Comments
-
techno about 4 years
Im trying to add some items to a Listview which i added using Xamarin.Forms markup in an xaml file. The button can be accessed by hooking with the click event.But since the listview is empty i need the event like
ondraw
like in winforms, so that i can hook to it when it is drawn.In the XAML file I have :
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="ButtonXaml.ButtonXamlPage"> <StackLayout> <Button Text="Tap for click count!" BorderWidth="10" TextColor="Red" HorizontalOptions="Center" Clicked="OnButtonClicked" /> <ListView HorizontalOptions="Center" /> </StackLayout> </ContentPage>
In the .cs file i have
using System; using Xamarin.Forms; namespace ButtonXaml { public partial class ButtonXamlPage { int count = 0; public ButtonXamlPage() { InitializeComponent(); } public void OnButtonClicked(object sender, EventArgs args) { ((Button)sender).Text = "You clicked me"; } } }
So should i hook to events in Listview or can i do something like
Resource.getElementbyID
like we do in android -
techno over 9 yearsThanks.It works, but the auto complete does not recognize it.
-
Dave Voyles over 7 yearsCan confirm. I run into this issue all of the time on Xamarin Studio and need to do this as well.
-
Tunvir Rahman Tusher about 7 yearsPls suggest if i want to access if from class in platform Specific project inherited from PageRenderer using ExportRenderer.