繁体   English   中英

在 xamarin.forms 中将标签从一页添加到另一页的列表视图

[英]Adding labels to a listview from one page to another in xamarin.forms

嗨,我仍然是一个初级程序员,所以这可能是一个微不足道的问题。 我正在 xamarin.forms 中创建一个应用程序,我想在“page2”上创建一个新的 label,其中包含来自“page1”上的用户输入的文本。 我认为问题在于我在页面之间导航的方式,因为我知道添加 label 代码有效,因为我尝试将它放在一个页面上并且有效。 但是当我尝试添加 label 然后导航到“page2”时,什么也没有。 现在我有一个带有两个按钮的“MainPage”,一个用于“page1”,一个用于“page2”我还尝试将“page2”的导航按钮放在用户输入的页面“page1”上。 我正在使用这个导航:

public MainPage()
    {
        InitializeComponent();
    }
    private void BestilClicked(object sender, EventArgs e)
    {
        Navigation.PushAsync(new Page1());
    }
    private void HentClicked(object sender, EventArgs e)
    {
        Navigation.PushAsync(new Page2());
    }

如果您发现更多相关代码,请随时说出来,我很乐意提供。 非常感谢:D

你需要将数据传递到下一页,像这样

Navigation.PushAsync(new Page1(SomeUserEntry.Text));

然后在Page1的构造函数中

public Page1(string input)
{
   // do something with input here
}

在 xamarin.forms 中将标签从一页添加到另一页的列表视图

是的,我们通常像 Jason 所说的那样通过我们的 ContentPage 的构造函数传递数据。

如果我们想在从 page1 返回到 page2 时保存传递的数据,我们可以为 page2 定义一个全局数据。

您可以参考以下代码:

public class MyData
{
    public static List<string> dataList = new List<string>();

}

页面1.xaml.cs

public partial class Page1 : ContentPage
{
    public Page1()
    {
        InitializeComponent();
    }

    private async void Button_Clicked(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(mEntry.Text))
        {
            // method 1: pass data by constructor
            await Navigation.PushAsync(new Page2(mEntry.Text));
        }
        else
        {
            await DisplayAlert("Alert", "The input is empty!", "OK");
        }

    }
}

页面2.xaml.cs

   public partial class Page2 : ContentPage
{
    public Page2(string input)
    {
        InitializeComponent();

        // here we can get the passed data from page1 and we can add the 
        //data  to MyData.dataList

        MyData.dataList.Add(input);
      
        // set the ItemsSource  for the mListView in page2
        mListView.ItemsSource = MyData.dataList;
    }
}

第2.xaml页

   <ContentPage.Content>
    <StackLayout  x:Name="mStackLayout">
        <Label Text="Welcome to Page2"
            VerticalOptions="Start" 
            HorizontalOptions="CenterAndExpand" />

        <ListView x:Name="mListView"  >
            
            
        </ListView>
    </StackLayout>
</ContentPage.Content>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM