如何通过 ContentPage 传递多个标签

how to pass multiple labels through ContentPage

我正在寻求帮助来设置隐藏代码以使用下一步按钮传递多个标签。基本上我想在页面打开时设置一个标签,按下一个按钮并用一个新标签替换当前标签(不设置新内容页面)。我是在 Xamarin.Forms 工作的初学者,我并不真正了解数据绑定过程...如果有人有很好的参考资料(Microsoft 网站除外)也会有所帮助。很确定下面的代码还不会做任何事情......提前致谢:)

这是内容页面:

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

                <Label Text="{Binding ItText}" />

            </StackLayout>
        </ScrollView>

后面的代码我是这样写的:

''''''

namespace MVVM2
{
public partial class MainPage : ContentPage
{
    List<MainPage> Contacts { get; set; }
    int ndx = 0;

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

    public MainPage()
    {
        InitializeComponent();

        Contacts = new List<MainPage>();

        // repeat this for as many contacts as you need
        Contacts.Add(new MainPage
        {
            TitleText = "Title1",
            EngText = "EngText1",
            ItText = "ItText1"
        });

        Contacts.Add(new MainPage
        {
            TitleText = "Title2",
            EngText = "EngText2",
            ItText = "ItText2"
        });

        Contacts.Add(new MainPage
        {
            TitleText = "Title3",
            EngText = "EngText3",
            ItText = "ItText3"
        });

        // display the first contact
        BindingContext = Contacts[ndx];
    }

    private 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]; 
        }
    }
  }
}

如果您只想在单击按钮时显示不同的文本,则不需要导航到新页面

首先,创建一个 List 来保存您的按钮和一个变量来跟踪显示的按钮。这两行应该在你的 class 的正文中,但不在任何特定方法中

List<Contact> contacts { get; set; }
int ndx = 0;

然后在你的构造函数中设置你的数据

public MainPage()
{
    InitializeComponent();
 
    contacts = new List<Contact>();

    // repeat this for as many contacts as you need
    contacts.Add(new Contact { 
        TitleText = "Title1",
        EngText = "EngText1",
        ItText = "ItText1"});
   
    // display the first contact
    BindingContext = contacts[ndx];
}

最后,处理按钮点击

async 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];
   }
}