简体   繁体   English

如何从另一个页面访问 ListView?(Xamarin Forms)

[英]How to access a ListView from another page?(Xamarin Forms)

I would like to modify the content of a list View from my MainPage.我想从我的 MainPage 修改列表视图的内容。 The list view is in another page called LoadResultsPage.列表视图位于另一个名为 LoadResultsPage 的页面中。 Here is the button in the main page which calls the function:这是主页面中调用该函数的按钮:

<Button Text="Load Results" Clicked="FetchData"></Button>

Here is the function which is called:这是调用的函数:

public async void FetchData(object sender, System.EventArgs e)
    {
        /* string apiUrl = null;
         if (Device.RuntimePlatform == Device.Android)
             apiUrl = "https://10.0.2.2:5001/api";
         else if (Device.RuntimePlatform == Device.iOS)
             apiUrl = "https://localhost:5001/api";
         else
             throw new Exception();*/
        await Navigation.PushAsync(new LoadResultsPage());
        var httpClient = new HttpClient();
        var response = await httpClient.GetStringAsync("http://localhost:5001/api/Calcs");
        var login = JsonConvert.DeserializeObject<List<Calc>>(response);
        Lista.ItemsSource = login;
    }

Here Lista(at the bottom of the function) is not recognized and the error is : "The name 'Lista' does not exist in the current context"此处 Lista(在函数底部)无法识别,错误为:“当前上下文中不存在名称 'Lista'”

And finally here is the content of the page LoadResultsPage where the list view that i want to modify is:最后这里是页面 LoadResultsPage 的内容,其中我要修改的列表视图是:

<?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="Calculator.Views.LoadResultsPage">
<Grid  VerticalOptions="FillAndExpand">
    <ListView x:Name="Lista" >
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell >
                    <StackLayout >
                        <Label Text="{Binding Id}" TextColor="Black"></Label>
                        <Label Text="{Binding Value}"></Label>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

How do i populate the two labels with the info in the variable "login" ?如何使用变量“登录”中的信息填充两个标签?

Please kindly read about MVVM that my change your concept globally.请仔细阅读我在全球范围内改变您的概念的 MVVM。 It is considered not a best style to access ui elements between pages.在页面之间访问 ui 元素被认为不是最佳样式。

Anyway directly answering your question use some static model to exchange data globally inside app.无论如何,直接回答您的问题使用一些静态模型在应用程序内全局交换数据。

    public class Exchange
    {
        private static Exchange _instance;
        public static Exchange Data
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new Exchange();
                }
                return _instance;
            }
        }

        public string Buffer { get; set; }

        public ListView MyListView { get; set; }

    }

Example: Exchange.Data.Buffer will be accessible from anywhere.示例:可以从任何地方访问Exchange.Data.Buffer

For your ListView in its page constuctor after the InitializeComponent();对于在InitializeComponent();之后的页面构造器中的 ListView InitializeComponent(); set

Exchange.Data.MyListView = Lista;

Now the important part that if you access your ListView from another page you have to do it on UI thread.现在重要的部分是,如果您从另一个页面访问 ListView,则必须在 UI 线程上执行此操作。 Example:例子:

        Device.BeginInvokeOnMainThread(() =>
        {
            // Update the UI
            Exchange.Data.MyListView.ItemsSource = whatever;
        });

The name field is not a public property, so by default it can not be accessed outside page. name 字段不是公共属性,因此默认情况下无法在页面外访问它。

There are two options for you question:你的问题有两种选择:

  1. Once you get the data (in your case "login") then only you navigate to LoadResultsPage and pass login as parameter and in LoadResultsPage, you will have access to "Lista".一旦您获得数据(在您的情况下为“登录”),那么只有您导航到 LoadResultsPage 并将登录作为参数传递,并且在 LoadResultsPage 中,您将可以访问“Lista”。

  2. Make a public property in LoadResultsPage, after getting "login", assign "login" to that property and in LoadResultsPage set Lista.ItemSource to that property.在 LoadResultsPage 中创建一个公共属性,在获得“登录”后,将“登录”分配给该属性,并在 LoadResultsPage 中将 Lista.ItemSource 设置为该属性。

Here suggesting that passing login data for LoadResultsPage , then can show the data when LoadResultsPage appears.这里建议为LoadResultsPage传递登录数据,然后可以在LoadResultsPage出现时显示数据。

For example, modifying FetchData method as follow:例如,修改FetchData方法如下:

public async void FetchData(object sender, System.EventArgs e)
{
    
    var httpClient = new HttpClient();
    var response = await httpClient.GetStringAsync("http://localhost:5001/api/Calcs");
    var login = JsonConvert.DeserializeObject<List<Calc>>(response);
    //Lista.ItemsSource = login;

    await Navigation.PushAsync(new LoadResultsPage(login));
}

Then in LoadResultsPage.xaml.cs :然后在LoadResultsPage.xaml.cs 中

public partial class DetailPage : ContentPage
{
    public DetailPage(Model login)
    {
        InitializeComponent();
        Lista.ItemsSource = login;
    }
}

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

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