Xamarin.Forms accessing controls written in markup

2019-01-27 18:23发布

问题:

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

回答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;


回答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");


回答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();
    }
    ...
}