passing RSS binded data to another page, windows phone 7
This may seem like an easy answer to someone, so I'm giving this a shot as I've doubled over trying to solve this.
I'm passing RSS information into a listbox
itemtemplate
with binded data. Each listboxitem has an image URL. I want the user to be abl开发者_StackOverflowe to click on the listboxitem, pass that image URL to a new page, and open up the page displaying the image.
Only problem? I cannot get this to work.
Here is what I have so far:
page1 XAML:
<ListBox x:Name="listbox" Grid.Row="1" SelectionChanged="listbox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image Grid.Row="0" HorizontalAlignment="Left" Height="60" Width="60" Source="{Binding Url}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Page1 cs
private void listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var URLname = "";
URLname = (sender as RssItem).Url.ToString();
NavigationService.Navigate(new Uri("/SubmittedPic.xaml?image=" + URLname, UriKind.Relative));
this.listbox.SelectedItem = (sender as ListBoxItem);
}
The code is breaking on URLname = (sender as RssItem).Url.ToString();
and it is saying that a null reference exception was unhandled.
Any help on this would be more than appreciated.
From your code I think you're confusing ListBoxItem
and the bound object RssItem
. If you're binding correctly, RssItem
will be the type of the object contained in the ListBoxItem.DataContext
.
To check this, use the debugger to see what type and value sender
actually is.
The following code works in my case: it takes the sender and gets its DataContext, and then casts it to the type of my bound object.
FrameworkElement fe = (FrameworkElement)sender;
RssItem rssItem = (RssItem) fe.DataContext;
string url = rssItem.URL.ToString();
Also, note that using SelectionChanged in this way could introduce subtle bugs in touch selection and when back-navigating to this list from your details page. To avoid these you should use a tap-event on your list item.
The SelectionChanged
event uses the standard EventHandler
pattern which all UI framework events conform to where the first argument sender
, of type object
, is the source UI element for the event. In this case, as the event is emitted by the ListBox
, sender will be a reference to your ListBox
.
To get the clicked item, you need to inspect the ListBox.SelectedItem
property. This should be your RssItem
.
It is worth noting that a ListBox
is not the best control for navigation, firstly it is a bit heavyweight (it has unnecessary UI elements that support selection), and secondly, you have to clear selection so that the same element can be clicked when you return back to the original list page.
You can find a dedicated navigation control here:
http://www.scottlogic.co.uk/blog/colin/2011/04/a-fast-loading-windows-phone-7-navigationlist-control/
精彩评论