Passing data from listbox navigation Windows Phone - json

I'm getting data to create a Listbox like a blog with JSON from a webblog, I want to pass this data when you select one item, to another simple xaml page with the information of this news(Title, content and Image). How can I get all the values for a new page with the information of the selected Item of the list?
I have this code for the listBox:
<ListBox x:Name="NewsList" Margin="0,200,0,0" ItemsSource="{Binding Items}" SelectionChanged="ListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17" Width="432" Height="100">
<!--Replace rectangle with image-->
<Image x:Name="Imagen" Height="100" Width="100" Margin="12,0,9,0">
<Image.Source>
<BitmapImage UriSource="{Binding LineThree}" />
</Image.Source>
</Image>
<StackPanel Width="311">
<TextBlock x:Name="Titulo" Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="18.667" FontFamily="Tahoma" Margin="12,0,12,6"/>
<TextBlock x:Name="Contenido" Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,0" Style="{StaticResource PhoneTextSubtleStyle}" FontSize="16"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I get the values from the news here :
Items is the list where I add the values of the news(Title, content, and Image)
public void LoadData()
{
WebRequest.RegisterPrefix("http://automaticband.es/blog/", WebRequestCreator.ClientHttp);
Uri serviceUri = new Uri("http://automaticband.es/blog/?json=get_recent_post");
WebClient downloader = new WebClient();
downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
downloader.OpenReadAsync(serviceUri);
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
Stream responseStream = e.Result;
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Posts));
Posts response = (Posts)ser.ReadObject(responseStream);
if (response.posts != null && response.posts.Count > 0)
{
foreach (Post post in response.posts)
{
this.Items.Add(new ItemViewModel() { LineOne = post.title, LineTwo = post.excerpt,
LineThree = post.thumbnail});
}
}
}
catch (Exception x)
{
return;
}
this.IsDataLoaded = true;
}
}
Thank you

I found the solution here :
http://windowsphonegeek.com/articles/Windows-Phone-MVVM-Master---Details-Navigation-in-5-minutes
Easy way to pass data between pages with ItemViewModel.

Related

How to add Buttons inside of MapControl Windows Phone 8.1

I want to put two Buttons in my MapControl, one to zoom in, and other to zoom out, here's my CS file with a code,what i did here i use the
MapControl1.ZoomLevel = 15; , but how i can put this inside a button?
public async void mapas2()
{
Geolocator geolocator = new Geolocator();
Geoposition geoposition = null;
try
{
geoposition = await geolocator.GetGeopositionAsync();
}
catch (Exception ex)
{
MessageDialog ms = new MessageDialog("Erro GPS, Por favor, acesse as configurações de seu Windows Phone," + Environment.NewLine +
"na opção LOCALIZAÇÃO e habilite o Serviço de Localização");
ms.ShowAsync();
}
MapControl1.Center = geoposition.Coordinate.Point;
MapControl1.ZoomLevel = 15;
MapIcon mapIcon = new MapIcon();
mapIcon.NormalizedAnchorPoint = new Point(0.25, 0.9);
mapIcon.Location = geoposition.Coordinate.Point;
mapIcon.Title = "Você está aqui....";
MapControl1.MapElements.Add(mapIcon);
}
You can place these buttons with your map control in one Grid in XAML, so the will look like they're on the map.
Example:
<Grid>
<Maps:MapControl />
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Bottom"
Orientation="Horizontal"
Margin="24">
<Button Content="+"
Margin="12"
MinWidth="40" />
<Button Content="-"
Margin="12"
MinWidth="40" />
</StackPanel>
</Grid>
Just few more lines to Łukasz Rejman answer
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Bottom" Orientation="Horizontal" Margin="15">
<Button x:Name="ZooOut" Content="-" Margin="5" MinWidth="60" MinHeight="60" Tapped="ZooOut_Tapped" />
<Button x:Name="ZoomIn" Content="+" Margin="5" MinWidth="60" MinHeight="60" Tapped="ZoomIn_Tapped" />
</StackPanel>
Button Tapped Event:
private void ZoomIn_Tapped(object sender, TappedRoutedEventArgs e)
{
if (CustomMapControl.ZoomLevel < 20)
{
if (CustomMapControl.ZoomLevel > 19)
CustomMapControl.ZoomLevel = 20;
else
CustomMapControl.ZoomLevel++;
}
}
private void ZooOut_Tapped(object sender, TappedRoutedEventArgs e)
{
if (CustomMapControl.ZoomLevel > 1)
{
if (CustomMapControl.ZoomLevel < 2)
CustomMapControl.ZoomLevel = 1;
else
CustomMapControl.ZoomLevel--;
}
}

Selection Changed Event is Rising when I clicked on Click Event handler

Sorry for the silly question.I even did not understand what should be given as title to this question.
I have 3 buttons and when I click them listboxes should be displayed.
And if I select an item in listbox it should be navigated and start playing.
When I click a button listbox is displaying and when an item is selected it is navigating to to other page and playing.After performing selection changed if I click any button I was getting error like
A first chance exception of type 'System.NullReferenceException' occurred in tori.dll
An unhandled exception of type 'System.NullReferenceException' occurred in tori.dll
Archieves .xaml:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,-951,0">
<Button Name="btn1" Click="btn1_Click" Content="Daily" HorizontalAlignment="Left" Margin="0,88,0,0" VerticalAlignment="Top" Width="127" Height="72"/>
<Button Name="btn2" Click="btn2_Click" Content="Weekly" HorizontalAlignment="Left" Margin="132,88,0,0" VerticalAlignment="Top" Height="72" Width="140"/>
<Button Name="btn3" Click="btn3_Click" Content="CurrentMonth" HorizontalAlignment="Left" Margin="277,88,0,0" VerticalAlignment="Top" Height="72" Width="169"/>
<ListBox x:Name="itemsList" Margin="0,225,945,0"
SelectionChanged="itemsList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="130">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image delay:LowProfileImageLoader.UriSource="{Binding ThumbnailUrl}"
Grid.Column="0"
Width="500"
Height="125"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="6"/>
<StackPanel Margin="10,20,0,0"
Grid.Column="1"
Height="60"
Orientation="Horizontal"
VerticalAlignment="Center">
<TextBlock Text="{Binding title}"
FontSize="40" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Archieves.xaml.cs:
namespace tori
{
public partial class Archieves : PhoneApplicationPage
{
public Archieves()
{
InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
WebClient downloader = new WebClient();
Uri uri = new Uri(" http://www.toucheradio.com/RSSFeed/rssDaily.php ", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ChannelDownloaded);
downloader.DownloadStringAsync(uri);
}
void ChannelDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XDocument document = XDocument.Parse(e.Result);
var queue = from item in document.Descendants("item")
select new Item
{
title = item.Element("title").Value
,
link = item.Element("link").Value
,
pubDate = item.Element("pubDate").Value
,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value
,
};
itemsList.ItemsSource = queue;
}
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
WebClient downloader = new WebClient();
Uri uri = new Uri(" http://www.toucheradio.com/RSSFeed/rssWeekly.php ", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Channel1Downloaded);
downloader.DownloadStringAsync(uri);
}
void Channel1Downloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XDocument document = XDocument.Parse(e.Result);
var queue = from item in document.Descendants("item")
select new Item
{
title = item.Element("title").Value
,
link = item.Element("link").Value
,
pubDate = item.Element("pubDate").Value
,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value
,
};
itemsList.ItemsSource = queue;
}
}
private void btn3_Click(object sender, RoutedEventArgs e)
{
WebClient downloader = new WebClient();
Uri uri = new Uri("http://www.toucheradio.com/RSSFeed/rssMonthly.php ", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Channel2Downloaded);
downloader.DownloadStringAsync(uri);
}
void Channel2Downloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XDocument document = XDocument.Parse(e.Result);
var queue = from item in document.Descendants("item")
select new Item
{
title = item.Element("title").Value
,
link = item.Element("link").Value
,
pubDate = item.Element("pubDate").Value
,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value
,
};
itemsList.ItemsSource = queue;
}
}
private void itemsList_SelectionChanged(Object sender, SelectionChangedEventArgs e)
{
var app = App.Current as App;
app.selectedItem = (Item)itemsList.SelectedItem;
this.NavigationService.Navigate(new Uri("/Details.xaml", UriKind.Relative));
}
Item.cs:
namespace tori
{
public class Item
{
public string title { get; set; }
public string ThumbnailUrl { get; set; }
public string link { get; set; }
public string pubDate { get; set; }
}
}
Details.xaml:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid Height="617" VerticalAlignment="Top" Margin="-27,96,0,0">
<Image x:Name="ThumbnailUrl"
Width="279"
Height="421"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="0,-29,204,225" />
<Image x:Name="Image1" Tap="Image1_Tap" Margin="46,430,354,92" Source="/Images/pausebutton.png"/>
<TextBlock x:Name="title" FontSize="30" TextWrapping="Wrap" Margin="284,57,-50,436" />
<TextBlock x:Name="pubDate" FontSize="25" Margin="284,186,10,363" />
<MediaElement x:Name="MediaElement1" AutoPlay="True" Margin="0,397,20,0" Height="94" VerticalAlignment="Top" />
Details.xaml.cs:
namespace tori
{
public partial class Details : PhoneApplicationPage
{
Item item;
public Details()
{
InitializeComponent();
var app = App.Current as App;
item = app.selectedItem;
title.Text = item.title;
pubDate.Text = item.pubDate;
ThumbnailUrl.Source = new BitmapImage(new Uri(item.ThumbnailUrl, UriKind.RelativeOrAbsolute));
string s = item.link;
string url = s.Replace("archivesplayer", "hostArchivesURLForMobile");
WebClient downloader = new WebClient();
Uri uri = new Uri(url,UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Channel3Downloaded);
downloader.DownloadStringAsync(uri);
}
void Channel3Downloaded(object sender, DownloadStringCompletedEventArgs e)
{
var textData = (string)e.Result;
Regex urlRegex = new Regex("<td height=\"25\" align=\"center\">(?<url>.*)</td>");
MatchCollection mc = urlRegex.Matches(textData);
string url = "";
if (mc.Count > 0)
{
url = mc[0].Groups["url"].Value;
MediaElement1.Source = new Uri(url, UriKind.Absolute);
MediaElement1.Play();
}
}
}
}
After performing selecting item if I click a button I was getting error in this line
title.Text = item.title;
Can anybody please tell me how can I overcome this null exception.When I click on a button selection changed event is raising instead of click event. I am unable to know the reason for this.
Please anybody help me with this.
many Thanks in advance.
When you change the ItemsSource, the SelectionChanged event is raised. I think whenever you change the ItemsSource, the selection is reset (that is - set to null (none selected)). And that's how it should be, otherwise an item that's not in the ItemsSource could be the SelectedItem which is just wrong.
Now, to fix your issue, just check if SelectedItem != null in itemsList_SelectionChanged method.
Something else about your code: the methods btn1_Click, btn2_Click and btn3_Click seem to only have minor differences, so you could put most of the code in one method and just pass it the url. That's even more important for the ChannelDownloaded methods (as they are much longer). Basically you want to reuse code as much as possible. That makes the code easier to read (as it's not 10 pages, but one, so to speak), and easier to maintain (if there's an error - you only need to fix it in one place).

Parsing rss feed using xml serializer

Can anybody please tell me how can I parse this Url
http://bitcast-r.v1.sjc1.bitgravity.com/objectinfo/MIB/radio/inbradio_play.xml
such that all items in feed except the first item should be displayed in listbox.I am unable to understand how to parse omiting the first item.
This is the code I was using for parsing.But in this case I was getting all items of a feed.
But I need not get first item (i.e) torilive.How can I parse such that I should not get first item
MainPage.xaml.cs:
public MainPage()
{
InitializeComponent();
// is there network connection available
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
MessageBox.Show("No network connection available!");
return;
}
// start loading XML-data
WebClient downloader = new WebClient();
Uri uri = new Uri("http://bitcast-r.v1.sjc1.bitgravity.com/objectinfo/MIB/radio/inbradio_play.xml", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ChannelDownloaded);
downloader.DownloadStringAsync(uri);
}
void ChannelDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XmlSerializer serializer = new XmlSerializer(typeof(Channel));
XDocument document = XDocument.Parse(e.Result);
Channel channel = (Channel)serializer.Deserialize(document.CreateReader());
listBox.ItemsSource = channel.Collection;
}
}
Channel.cs:
namespace Sample
{
[XmlRoot("rss")]
public class Channel
{
[XmlArray("channel")]
XmlArrayItem("item")]
public ObservableCollection<Items> Collection { get; set; }
}
}
Items.cs:
namespace Sample
{
public class Items
{
[XmlElement("title")]
public string title { get; set; }
[XmlElement("link")]
public string link { get; set; }
[XmlElement("image")]
public string image { get; set; }
}
}
Hope anybody helps.Many Thanks in advance.
Nice program :)
C#
void ChannelDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XmlSerializer serializer = new XmlSerializer(typeof(Channel));
XDocument document = XDocument.Parse(e.Result);
Channel channel = (Channel)serializer.Deserialize(document.CreateReader());
// remove the first item
if (channel.Collection.Count > 0)
channel.Collection.RemoveAt(0);
this.myListBox.ItemsSource = channel.Collection;
}
}
XAML
<ListBox x:Name="myListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="0,0,0,1" BorderBrush="Red">
<StackPanel>
<TextBlock Text="{Binding title}"></TextBlock>
<TextBlock Text="{Binding link}" Width="350"></TextBlock>
<Image Source="{Binding image}" Width="50" Height="50" HorizontalAlignment="Left" VerticalAlignment="Top"></Image>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code In Action:
You can modify the template to get your desired results.

Parsing Xml feed having multiple different categories

Can anybody please tell me how can I parse the below Feed
http://teluguone.com/movies/moviesXml.php
In MainPage I will Arrange 8 Buttons like Action,
Comedy,
Love etc as based on different categories given in above feed.
When I click Action Button.The movies present in the Action Category has to be displayed in listbox.
And similarly when clicked on the other buttons also movies related to that particular categories has to be displayed in ListBox.
Anybody please give me hint how can I parse this feed with different categories.I am not understanding how can I parse these different categories.
I have written the following code to download xml file.Does it works.please tell me.
MainPage.Xaml:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="moviesList" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="130">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image delay:LowProfileImageLoader.UriSource="{Binding MovieImage}"
Grid.Column="0"
Width="97"
Height="125"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="6"/>
<StackPanel Margin="10,15,0,0"
Grid.Column="1"
Height="60"
Orientation="Horizontal"
VerticalAlignment="Top">
<TextBlock Text="{Binding MovieName}"
FontSize="30" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Mainpage.xaml.cs:
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// is there network connection available
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
MessageBox.Show("No network connection available!");
return;
}
// start loading XML-data
WebClient downloader = new WebClient();
Uri uri = new Uri("http://teluguone.com/movies/moviesXml.php", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(MoviesDownloaded);
downloader.DownloadStringAsync(uri);
}
void MoviesDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XmlSerializer serializer = new XmlSerializer(typeof(Movies));
XDocument document = XDocument.Parse(e.Result);
Movies movies = (Movies)serializer.Deserialize(document.CreateReader());
moviesList.ItemsSource = movies.Collection;
}
}
}
}
Movie.cs:
public class Movie
{
[XmlElement("MovieName")]
public string MovieName { get; set; }
[XmlElement("MovieActor")]
public string MovieActor { get; set; }
[XmlElement("MovieActress")]
public string MovieActress { get; set; }
[XmlElement("MovieDirector")]
public string MovieDirector { get; set; }
[XmlElement("MovieImage")]
public string MovieImage { get; set; }
}
Movies.cs:
[XmlRoot("Movies")]
public class Movies
{
[XmlArray("movies")]
[XmlArrayItem("movie")]
public ObservableCollection<Movie> Collection { get; set; }
}
ManyThanks in Advance
First understand basic XML structure and write properties based on that. Its very long to describe here, hence I have uploaded my sample project "XML deserialization into C# objects" in GitHub and refer for more info.
Step 1: Write properties based on XML Structure, which your retrieve from Source.
Step 2: Download the XML string using WebClient or Http class.
Step 3: Deserialize those strings using XMLSerializer and bind it to objects.
Step 4: Get respective terms using providing search options from objects.
You can refer my GitHub Project here.

ContextMenu selects old item

So basically this is the situation. I have a longlistselector that shows data (say, a list of cars):
<phone:LongListSelector x:Name="list" ItemsSource="{Binding CarList}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Click="DeleteMenuItem_Click" Header="delete"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<TextBlock Text="{Binding SomeText}">
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
And then this is how I handle the deletion:
private void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
{
Car data = (sender as MenuItem).DataContext as Car;
using (var db = new SQLiteConnection(App.DBpath))
{
var existing = db.Query<Feed>("select * from Cars where Id = " + data.Id.ToString()).FirstOrDefault();
if (existing != null)
{
db.RunInTransaction(() =>
{
db.Delete(existing);
});
App.ViewModel.loadCarData();
}
}
}
Now the issue is that after deleting few, the context menu starts to give old selection and does not update which makes var existing = db.Query<Feed>("select * from Cars where Id = " + data.Id.ToString()).FirstOrDefault(); return null obviously because it has been already deleted from database. Any idea how to fix this?
Probably this issue.
private void ContextMenu_Unload(object sender, RoutedEventArgs e)
{
ContextMenu conmen = (sender as ContextMenu);
conmen.ClearValue(FrameworkElement.DataContextProperty);
}