簡體   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