Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.Forms accessing controls written in markup from Code

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.

enter image description here

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

like image 712
techno Avatar asked Oct 14 '14 05:10

techno


2 Answers

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;
like image 85
Jason Avatar answered Sep 25 '22 20:09

Jason


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");
like image 44
Thomas Hagström Avatar answered Sep 24 '22 20:09

Thomas Hagström