Xamarin.Forms从代码访问以标记编写的控件 [英] Xamarin.Forms accessing controls written in markup from Code

查看:229
本文介绍了Xamarin.Forms从代码访问以标记编写的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些项目添加到我使用Xaml文件中的Xamarin.Forms标记添加的Listview中. 可以通过单击click钩子来访问该按钮.但是由于listview为空,因此需要像winforms中的ondraw这样的事件,以便在绘制时可以钩住它.

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.

在XAML文件中,我有:

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>

在.cs文件中,我有

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";
        }
    }
}

所以我应该挂接到Listview中的事件,还是可以像我们在android中一样做类似Resource.getElementbyID的事情?

So should i hook to events in Listview or can i do something like Resource.getElementbyID like we do in android

推荐答案

要在后面的代码中访问Forms控件,您需要使用x:Name属性为它分配一个名称

To access a Forms control in the code-behind, you need to assign it a name, using the x:Name attribute

在XAML中:

<ListView HorizontalOptions="Center" x:Name="MyList" />

使用代码:

MyList.ItemsSource = myData;

这篇关于Xamarin.Forms从代码访问以标记编写的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆