简体   繁体   English

从ListView SelectedItem传递JSON对象数据

[英]Passing json object data from a ListView SelectedItem

I need some help with passing the ListView Tapped Id (which I get from a json). 我需要一些有关传递ListView Tapped Id(我从json获得)的帮助。

I populate the listView with an API call to a server: 我使用对服务器的API调用填充listView:

        private async void searchButton_Click(object sender, RoutedEventArgs e)
    {
        var textFrom = odTextBox.Text;
        var textTo = doTextBox.Text;
        var searchResult = await PrevoziApi.SearchRidesAsync(textFrom, textTo, datePicker.Date.UtcDateTime);
        var array = searchResult.CarshareList
                .OrderBy(cs => cs.Time)
                .Select(cs => cs.Contact + " " + cs.Time)
                .ToArray();
            listView.ItemsSource = array;
    }

Now, when I click on an item of listView, I want to navigate to another page(CarShareDetailedPage) and make another call to the API, to get more detailed data about that item. 现在,当我单击listView的项目时,我想导航到另一个页面(CarShareDetailedPage)并再次调用API,以获取有关该项目的更多详细数据。 So I need to pass the selectedItem id from one page to other. 因此,我需要将selectedItem ID从一页传递到另一页。 How do I do that ? 我怎么做 ?

I'm navigating to another page like this: 我正在导航到另一个这样的页面:

        private void listView_Tapped(object sender, TappedRoutedEventArgs e)
    {
        Frame.Navigate(typeof(CarShareDetailedPage), listView.SelectedIndex);
    }

The OnNagiatedMethod on that page is: 该页面上的OnNagiatedMethod是:

        protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        var value = e.ToString();
        carShareTextBox.Text = value;
    }

And my json class is: 我的json类是:

public class CarshareList
    {
        [JsonProperty("id")]
        public int Id { get; set; }
        [JsonProperty("type")]
        public string Type { get; set; }
        [JsonProperty("from_id")]
        public string FromId { get; set; }
        [JsonProperty("from_country")]
        public string FromCountry { get; set; }
        [JsonProperty("from_country_name")]
        public string FromCountryName { get; set; }
        [JsonProperty("to_id")]
        public string ToId { get; set; }
        [JsonProperty("to")]
        public string To { get; set; }
        [JsonProperty("to_country")]
        public string ToCountry { get; set; }
        [JsonProperty("to_country_name")]
        public string ToCountryName { get; set; }
        [JsonProperty("time")]
        public string Time { get; set; }
        [JsonProperty("date_iso8601")]
        public DateTime DateIso8601 { get; set; }
        [JsonProperty("added")]
        public DateTime Added { get; set; }
        [JsonProperty("price")]
        public double? Price { get; set; }
        [JsonProperty("num_people")]
        public double NumPeople { get; set; }
        [JsonProperty("author")]
        public string Author { get; set; }
        [JsonProperty("is_author")]
        public string IsAuthor { get; set; }
        [JsonProperty("comment")]
        public string Comment { get; set; }
        [JsonProperty("contact")]
        public string Contact { get; set; }
        [JsonProperty("date")]
        public string Date { get; set; }
        [JsonProperty("full")]
        public string Full { get; set; }
        [JsonProperty("insured")]
        public string Insured { get; set; }
        [JsonProperty("share_type")]
        public string ShareType { get; set; }
        [JsonProperty("confirmed_contact")]
        public string ConfirmedContact { get; set; }
        [JsonProperty("bookmark")]
        public object Bookmark { get; set; }
        [JsonProperty("from")]
        public string From { get; set; }
    }

    public class CarshareResponse
    {
        [JsonProperty("search_type")]
        public string SearchType { get; set; }
        [JsonProperty("carshare_list")]
        public IList<CarshareList> CarshareList { get; set; }
    }

Let me say this is the first time ever I'm doing any work with Apis and json. 我说这是我第一次使用Apis和json做任何工作。 Thanks for your help! 谢谢你的帮助!

EDIT: I added the code for the API below, so this now should be all the code I have. 编辑:我添加了下面的API的代码,所以现在这应该是我所有的代码。

public class PrevoziApi
{ public static async Task<CarshareResponse> SearchRidesAsync(
    string fromCity, 
    string toCity, 
    DateTime date, 
    string type = "shares", 
    CancellationToken token = default(CancellationToken))
    {
        using (var client = new RestClient("https://prevoz.org/api/"))
        {
                var request = new RestRequest("search/" + type + "/", HttpMethod.Get);
                request.AddQueryParameter("f", fromCity);
                request.AddQueryParameter("fc", "SI");
                request.AddQueryParameter("t", toCity);
                request.AddQueryParameter("tc", "SI");
                request.AddQueryParameter("d", date.ToString("yyyy-MM-dd"));
                request.AddQueryParameter("exact", "true");
                return
                    (await client.Execute<CarshareResponse>(request, token)).Data;
            }
    }
}

So with this, you are ordering by the time but displaying a string only that says "[Contact] [Time]". 因此,您可以按时间排序,但只显示一个字符串,显示“ [Contact] [Time]”。 This in-and-of-itself does not hold any relation to the JSON that was returned from your search method. 它本身并不与您的搜索方法返回的JSON有任何关系。 What you'll want to do is instead of making it an array, instead making a List<> object that can store some additional "background" data about that request to send off. 您要做的不是将其制成数组,而是创建一个List <>对象,该对象可以存储有关该发送请求的其他“背景”数据。

This will require a bit more effort though on your end. 尽管这需要您付出更多的努力。 You will want to create a class 您将要创建一个类

public class CarItemView {
    public string DisplayText {get; set;}
    public int ID {get; set;}
}

and fill it with whatever data you want to pass along. 并用您想要传递的任何数据填充它。 Then in your filtering you would do: 然后在过滤中,您将执行以下操作:

List<CarItemView> array = searchResult.CarshareList
            .OrderBy(cs => cs.Time)
            .Select(cs => new { DisplayText = cs.Contact + " " + cs.Time, ID = cs.Id}).ToList();

You will then, in your XAML, have to add a template to your listview for display. 然后,您将必须在XAML中将模板添加到列表视图中才能显示。 (Note, this is a real rough outline for a XAML Template) (请注意,这是XAML模板的真实概述)

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding DisplayText}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

NOW when you get your selected item changed event fired, you can handle it and get the ID. 现在,当您触发选定项目更改事件时,您可以处理它并获取ID。

private void listView_Tapped(object sender, TappedRoutedEventArgs e)
{
    var obj = (CarItemView) listView.SelectedItem; // convert item to our new class
    Frame.Navigate(typeof(CarShareDetailedPage), obj.Id.ToString()); // send ID as string
}

Then for the receiving page: 然后对于接收页面:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var value = e.ToString();
    carShareTextBox.Text = value; // will show the ID number

    var caritemret = /* write a new restful function to return based on ID */
}

UPDATE: This answer was updated from original to reflect the use of an array instead of a list<> object 更新:此答案已从原始版本更新为反映使用数组而不是list <>对象的方法

I hope this helps! 我希望这有帮助!

This works: 这有效:

        private async void searchButton_Click(object sender, RoutedEventArgs e)
    {
        var textFrom = odTextBox.Text;
        var textTo = doTextBox.Text;
        var searchResult = await PrevoziApi.SearchRidesAsync(textFrom, textTo, datePicker.Date.UtcDateTime);

        List<CarItemView> array = searchResult.CarshareList
                                  .OrderBy(cs => cs.Time)
                                  .Select(cs => new CarItemView { DisplayText = cs.Contact + " " + cs.Time, Id = cs.Id })
                                  .ToList();
        listView.ItemsSource = array;
    }

        private void listView_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
    {
        var obj = (CarItemView)listView.SelectedItem; // convert item to our new class
        Frame.Navigate(typeof(CarShareDetailedPage), obj.Id); // send ID as string        
    }

And on navigated to method on the destination page: 并导航到目标页面上的方法:

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        var value = e.Parameter.ToString();
        carShareTextBox.Text = value; // will show the ID number

        /* write a new restful function to return based on ID */
    }

Thanks @daniel, it was mostly as you suggested, with a few errors, but with the help of some guys at the c# chat channel I managed. 感谢@daniel,它基本上是您所建议的,有一些错误,但是在我管理的C#聊天频道的一些人的帮助下。 Thanks to all. 谢谢大家。

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

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