首页 > 解决方案 > Xamarin.Forms 中的设置列表

问题描述

我正在构建一个应用程序,当您单击下一步按钮时,它将使用后面的代码通过绑定提供新文本。每次我将页面设置为在虚拟电话上加载时,热重载都会超时……最糟糕的是,我也没有收到任何错误。有任何想法吗?

内容页:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="List.MainPage">

<ContentPage.Content>
    <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
         <Label Text="{Binding TitleText}" />
        <ScrollView VerticalOptions="FillAndExpand">
            <StackLayout>
                <Label Text="{Binding EngText}" />

                <Label Text="{Binding ItText}" />
            </StackLayout>
        </ScrollView>
        <Button Text="Next Page" Clicked="OnNavigateButtonClicked" />
    </StackLayout>
</ContentPage.Content>

代码背后:

using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace List
{
  public partial class MainPage : ContentPage
  {
    List<MainPage> Contacts { get; set; }
    public string TitleText { get; set; }
    public string EngText { get; set; }
    public string ItText { get; set; }

    int ndx = 0;

    public MainPage()
    {
        InitializeComponent();

        Contacts = new List<MainPage>
        {

            // repeat this for as many contacts as you need
            new MainPage
            {
                TitleText = "Title1",
                EngText = "EngText1",
                ItText = "ItText1"
            },
            new MainPage
            {
                TitleText = "Title2",
                EngText = "EngText2",
                ItText = "ItText2"
            },
        };

        // display the first contact
        BindingContext = Contacts[ndx];
    }
    void OnNavigateButtonClicked(object sender, EventArgs e)
    {
        // increment your index
        ndx++;

        // check that we haven't gone too far
        if (ndx < Contacts.Count)
        {
            BindingContext = Contacts[ndx];
        }
    }
 }
}

标签: xamarin.forms

解决方案


MainPage您正在为您的 UI 和数据使用相同的类。的构造函数MainPage创建 2 个新的 `MainPage 实例,每个实例调用它们的构造函数并再创建 2 个实例,这将永远递归,直到您使用所有内存并崩溃

你需要两个不同的类,一个用于你的 UI,一个用于你的数据

public class Data
{
    public string TitleText { get; set; }
    public string EngText { get; set; }
    public string ItText { get; set; }
}

public partial class MainPage : ContentPage
{
 List<Data> Contacts { get; set; }

int ndx = 0;

public MainPage()
{
    InitializeComponent();

    Contacts = new List<Data>
    {

        // repeat this for as many contacts as you need
        new Data
        {
            TitleText = "Title1",
            EngText = "EngText1",
            ItText = "ItText1"
        },
        new Data
        {
            TitleText = "Title2",
            EngText = "EngText2",
            ItText = "ItText2"
        },
    };

推荐阅读