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

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

问题描述

我正在尝试将一些项目添加到我在 xaml 文件中使用 Xamarin.Forms 标记添加的 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 文件中我有

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

那么我应该挂钩 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天全站免登陆