How to get the listbox item's properties after

2019-08-31 04:53发布

问题:

I have a custom listbox. Some of the collections's items have fields "name", "text", "image" and "url". Other may have other fields (a use a template selector). So, if item has fields "name", "text", "url" and "image" - it shows in listbox as 2 textblocks and 1 image. When I tap on the image - program must open new window, open webBrowser and go to url wich is in the item's property "url". I understand how to transmit info from one page to other, but i cant understand how to get the "url" from item. I tried

    private void Video_Tap(object sender, GestureEventArgs e) // event when tap on the image
    {
        New tmp = ((sender as ListBox).SelectedItem as New); // New - is the type of collection's item
        string vid = tmp.Video.url; // Video has fields "image" and "url"

        string destination = string.Format("/Video_Page.xaml?uri={0}", vid );
        NavigationService.Navigate(new Uri(destination, UriKind.Relative));
    }

but sender has an image type.

回答1:

You can call Parent of the Image sender to get its container (or call it multiple times, depending on how your xaml is structured), then look into the container's Children to find the textbox you are looking for. For example, maybe you'd want to do something like this (with setting the Tag property of the textbox that contains your url in xaml).

var grid = (Grid) ((Image) sender).Parent;
foreach (var child in grid.Children)
{
    if (child is TextBox && ((TextBox) child).Tag == "URL")
    {
        return (Textbox) child;
    }
}

Or, if you just want an always-available reference to the ListBox, just set its x:Name = "_MyListbox" in xaml, and it will become a field of the class.

As a final option, I'm thinking it might just be easier for you to bind to ListBox.SelectedItem, so that you always have some property that contains the currently selected New item.