I have the following problem :
this is my xaml code:
<ListBox Grid.Row="1" Name="ResultsView">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel Width="340">
<TextBlock TextWrapping="Wrap" Text="{Binding Path=Title}"/>
<TextBlock FontWeight="Bold" Text="{Binding Path=Author}"/>
<TextBlock Text="{Binding Path=Published}"/>
<TextBlock Text="{Binding Path=Guid}"/>
<TextBlock Text="{Binding Path=Link}"/>
<TextBlock Text="{Binding Path=Description}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and this my code for binding the listbox:
private void Feed(object Sender, DownloadStringCompletedEventArgs e)
{
XElement _xml;
try
{
if (!e.Cancelled)
{
_xml = XElement.Parse(e.Result);
ResultsView.Items.Clear();
foreach (XElement value in _xml.Elements("channel").Elements("item"))
{
Tweet _item = new Tweet();
_item.Title = value.Element("title").Value;
_item.Author = value.Element("author").Value;
_item.Published = DateTime.Parse(value.Element("pubDate").Value);
_item.Guid = value.Element("guid").Value;
_item.Link = value.Element("link").Value;
_item.Description = Regex.Replace(value.Element("description").Value,
#"<(.|\n)*?>", String.Empty);
ResultsView.Items.Add(_item);
MessageBox.Show("test");
}
}
}
catch
{
// Ignore Errors
}
}
the code when i launch the binding:
private void Lookup_Click(object sender, RoutedEventArgs e)
{
WebClient _client = new WebClient();
_client.DownloadStringCompleted += Feed;
_client.DownloadStringAsync(new Uri((_value + Location.Text)));
}
and this is the rss feed : rss feed link
here is indeed a valid rss feed but I never add an item to my listbox. (the alert is never displayed) and I can not find out why. Someone would have an idea? Thanks in advance.
Your main issue is that you ignore XML namespaces in the feed.
It should look something like:
XNameSpace ns = ...;
foreach (XElement value in _xml.Elements( ns + "channel").Elements(ns + "item"))
...
See this Question for some RSS related examples.
After that, I'm not so sure that a DataTemplate is applied to Items. Customary is to bind through the ItemsSource property.
And don't use _ on local variables names. They are only to be used like that on private fields.
Related
I am a new developer on Windows Phone 8.1, I am try to reach a specific ListView item from the ListView collection and be able to color it or color the TextBock inside of it, But I can't reach the item or reach any of items inside of ListView, Please take a look for my below code :
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
SQLiteRT db1 = new SQLiteRT();
var db_connection = await db1.Connection("MyDB.sqlite");
List<MyTBL> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;");
db_connection.Close();
LV_Options.ItemsSource = t_list;
}
// my List View called LV_Options
private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView lv1 = sender as ListView;
if (lv1 == null)
return;
MyTBL wrd = lv1.SelectedItem as MyTBL;
if (wrd == null)
return;
TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;
tb.FontSize = 17; // here I got debug error (it not worked !!!!!!!)
var item = LV_Options.Items.ElementAt(3); // this seems not work also !!!!
item.BackColor = Color.LightSteelBlue;
}
As you can see above, I tried to reach a specific item by LV_Options.Items.ElementAt(3) but it doesn't work! I also tried to reach the TextBlock from the selected List view item, but also not worked !
(Updated)
XAML code :
<!-- Title Panel -->
<StackPanel Grid.Row="0" Margin="19,0,0,0">
<TextBlock Name="TB_Rslt" Text="Here result of your answer" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
<TextBlock Text="page title" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
</StackPanel>
<!--TODO: Content should be placed within the following grid-->
<Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,10,19,15">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Name="TB_Question" Text="Choose Answer " Margin="0,0,25,0" HorizontalAlignment="Right" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" />
<TextBlock Name="TB_EnWord" Text="" Margin="90,0,15,0" HorizontalAlignment="Left" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" TextAlignment="Right" />
<StackPanel Grid.Row="1" Margin="5,22,0,0">
<ListView Name="LV_Options" SelectionChanged="LV_Options_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6">
<StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Name="TB_AMean1" Text="{Binding AMean1}" TextWrapping="Wrap"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
<Button Name="Btn_Answer" Content="Ansewr" HorizontalAlignment="Left" Grid.Row="1" VerticalAlignment="Bottom" Click="Btn_Answer_Click"/>
My application is a quiz application that offer 4 choices/options as answers for each question, and when user select a true answer, I want to highlight the true answer(true choice) by make its background to green, and if the user selected wrong answer/option I want to make the background of that answer (a specific List View item) with red.
Any help please ?
You're not going to be able to access an element inside a data template like that. Instead, leverage the binding to a view model to set the color and other view-related properties. First, create a wrapper view model for your data class:
public class MyTBLViewModel : INotifyPropertyChanged
{
public MyTBL Entity
{
get { return _entity; }
}
private readonly MyTBL _entity;
public Brush Highlight
{
get { return _brush; }
set
{
_brush = value;
RaisePropertyChanged("Highlight");
}
}
private Brush _highlight;
public double ItemFontSize
{
get { return _itemFontSize; }
set
{
_itemFontSize = value;
RaisePropertyChanged("ItemFontSize");
}
}
private Brush _itemFontSize;
public MyTBLViewModel(MyTBL entity)
{
_entity = entity;
_highlight = new SolidColorBrush(Colors.Transparent);
_itemFontSize = 12;
}
public event PropertyChangedEventArgs PropertyChanged;
protected void RaisePropertyChanged(string propName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propName));
}
}
Use this as your ItemsSource:
List<MyTBLViewModel> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;")
.AsEnumerable().Select(entity => new MyTBLViewModel(entity)).ToList();
Now in your view, bind the view elements to "Highlight" and "ItemFontSize", and to any other properties you like:
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6" Background="{Binding Highlight}">
<StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Name="TB_AMean1" Text="{Binding Entity.AMean1}" TextWrapping="Wrap"
FontSize="{Binding ItemFontSize}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
Finally, you can get the data item from the SelectionChangedEventArgs -- use it to update your view-related properties:
private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var item in e.AddedItems.OfType<MyTBLViewModel>())
{
item.Highlight = new SolidColorBrush(Color.LightSteelBlue);
item.ItemFontSize = 17;
}
foreach (var item in e.RemovedItems.OfType<MyTBLViewModel>())
{
item.Highlight = new SolidColorBrush(Colors.Transparent);
item.ItemFontSize = 12;
}
}
var item = LV_Options.Items.ElementAt(3);
This line is incorrect. It will not return you a TextBlock. I don't know what a .BackColor is, and it should not compile. The Items property in a ListView will return you a list of ListViewItems. If you want to access the inside element from a ListViewItem, you'll need to access the ContentTemplateRoot property.
Do not use var ever. It lets you assume that you know the type, whereas if you explicitly typed the declaration you would realize you're doing it wrong.
MyTBL wrd = lv1.SelectedItem as MyTBL;
if (wrd == null)
return;
TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;
What is a MyTBL type? FindName is only available to framework DependencyObjects so I'm assuming it's a user control? You have to provide a lot more code to show us what you're doing and what you're setting the ListView's ItemsSource and ItemTemplate with and what these errors are and how you have 2 breaking debug errors at once and what the error messages are.
Comprehending runtime error messages is a huge part of being a good developer.
I am building an application for Windows Phone 7 where in a ListBox I am showing data from the web service.
The WebService contains the following data:
News Title, News Description, Date Start and image path.
In the list box I am showing News Title, Date Start and image path.
Now on clicking an item from the list box I want to navigate to another page which should show all the three details along with news description.
My xaml is:
<ListBox Name="listBox1" SelectionChanged="listBox1_SelectionChanged">
<!-- SelectionChanged="listBox1_SelectionChanged"-->
<ListBox.ItemTemplate>
<DataTemplate>
<Button>
<Button.Content>
<ScrollViewer HorizontalScrollBarVisibility="Auto" Height="80" Width="400">
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<Image Source="{Binding ImageBind }" Height="80" Width="120"/>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=News_Title}" TextWrapping="Wrap"></TextBlock>
<!-- <TextBlock Text="{Binding Path=News_Description}" TextWrapping="Wrap"></TextBlock>-->
<TextBlock Text="{Binding Path=Date_Start}" TextWrapping="Wrap" ></TextBlock>
</StackPanel>
</StackPanel>
</ScrollViewer>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The .cs file is:
public News()
{
InitializeComponent();
KejriwalService.aapSoapClient client = new KejriwalService.aapSoapClient();
client.getarvindNewsCompleted += new EventHandler<KejriwalService.getarvindNewsCompletedEventArgs>(client_getarvindNewsCompleted);
client.getarvindNewsAsync();
progressName.Visibility = System.Windows.Visibility.Visible;
}
void client_getarvindNewsCompleted(object sender, KejriwalService.getarvindNewsCompletedEventArgs e)
{
string result = e.Result.ToString();
List<Newss> listData = new List<Newss>();
XDocument doc = XDocument.Parse(result);
progressName.Visibility = System.Windows.Visibility.Collapsed;
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
//data.News_Description = location.Element("News_Description").Value;
data.Date_Start = location.Element("Date_Start").Value;
data.image_path = location.Element("image_path").Value;
data.ImageBind = new BitmapImage(new Uri( #"http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/"+data.image_path, UriKind.Absolute));
listData.Add(data);
}
listBox1.ItemsSource = listData;
}
Now in a new page say newsdetails.xaml i want to navigate from this page and show the complete details.
Please help.
I am stuck in this as I am new in this domain.
I am almost done with my app if this is done.
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listBox1.SelectedIndex == -1)
return;
var item = listBox1.SelectedItem as Newss;
if (!IsolatedStorageSettings.ApplicationSettings.Contains("SelectedObject"))
{
IsolatedStorageSettings.ApplicationSettings["SelectedObject"] = item;
NavigationService.Navigate(new Uri("/NewsDetails.xaml", UriKind.Relative));
}
}
Define static global variables in that page where your listbox selection change event is:
public static string title;
public static string news_description;
On listbox selection change assign these variables:
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listBox1.SelectedIndex == -1)
return;
var item = listBox1.SelectedItem as Newss;
if (!IsolatedStorageSettings.ApplicationSettings.Contains("SelectedObject"))
{
IsolatedStorageSettings.ApplicationSettings["SelectedObject"] = item;
title=item.News_Title;
news_description=item.News_Description;
NavigationService.Navigate(new Uri("/NewsDetails.xaml", UriKind.Relative));
}
}
And in your navigation NewsDetails.cs page Access these items like this:
string Title=YourPageName.title;//
string Description=YourPageName.news_description;
show these values as you want
I have a list and want to assign the downloaded feeds her. Also wanted to say that I am using the same code I've used in another app, but is giving an error as few as this. The other works perfectly. I will post few as the source of this. For if you can not stay too long.
private void carregaListas()
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new System.Uri("http://www.news-medical.net/syndication.axd?format=rss"));
}
private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
stkLife.Visibility = Visibility.Visible;
stbOfLife.Begin();
});
}
else
{
// Save the feed into the State property in case the application is tombstoned.
//gridProgressBar.Visibility = Visibility.Collapsed;
this.State["feed"] = e.Result;
UpdateFeedList(e.Result);
}
}
private void UpdateFeedList(string feedXML)
{
StringReader stringReader = new StringReader(feedXML);
XmlReader xmlReader = XmlReader.Create(stringReader);
SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
feedListBox.ItemsSource = feed.Items;
});
}
Error: "Items collection must be empty before using ItemsSource."
XAML code:
<ListBox x:Name="feedListBox" Margin="0,0,-12,0" SelectionChanged="feedListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17">
<StackPanel.Background>
<SolidColorBrush Color="#FFC5C5C5" Opacity="0.35"/>
</StackPanel.Background>
<TextBlock Text="{Binding Title.Text, Converter={StaticResource RssTextTrimmer}}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="White" FontSize="30"/>
<TextBlock Text="{Binding Summary.Text, Converter={StaticResource RssTextTrimmer}}" TextWrapping="Wrap" Style="{StaticResource PhoneTextSubtleStyle}" Foreground="#99FFFFFF"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
I Have used this sample: http://code.msdn.microsoft.com/wpapps/RSS-Reader-Sample-1702775f
I already have a ListBox in my Code and now I added a new one:
<ListBox x:Name="Diaryresult"
Foreground="Black"
Margin="19,0,0,8">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Binding {name}"
FontSize="24" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I am populating this list with following code:
XElement diary = XElement.Parse(e.Result);
IEnumerable<XElement> diaryelements = diary.Elements("diaryelement");
List<Produkt> diaryprodukte = new List<Produkt>();
foreach (XElement diaryelement in diaryelements)
{
Produkt p = new Produkt();
p.name = diaryelement.Element("diaryshortitem").Element("description").Element("name").Value;
p.shortfacts = diaryelement.Element("diaryshortitem").Element("data").Element("kj").Value + " KJ - "
+ diaryelement.Element("diaryshortitem").Element("data").Element("kcal").Value + "kcal";
diary.Add(p);
Debug.WriteLine("Added "+p.name);
}
Diaryresult.ItemsSource = diaryprodukte;
Diaryresult.Visibility = System.Windows.Visibility.Visible;
But, it doesn't show up. Does anyone see the trick?
Your binding tag isn't correct. "Binding {Name}" doesn't means anything for XAML. {Binding Name} means to databind the property Name of your context which is what you're trying to do.
Replace:
<TextBlock Text="Binding {name}" FontSize="24" />
With:
<TextBlock Text="{Binding name}" FontSize="24" />
Also you need to add the element to the list:
dairyprodukt.Add(p);
And, remember to call your NotifyPropertyChanged() once done in order to notify the UI Thread of the changes. I mean, you're using Diaryresult.Visibility = System.Windows.Visibility.Visible; is this your way to notify your UI, are you using MVVM or CodeBehind?
It doesn't look like you are adding your Produkt to dairyprodukte. dairyprodukte is still an empty list when you bind it.
try
foreach (XElement diaryelement in diaryelements)
{
Produkt p = new Produkt();
p.name = diaryelement.Element("diaryshortitem").Element("description").Element("name").Value;
p.shortfacts = diaryelement.Element("diaryshortitem").Element("data").Element("kj").Value + " KJ - "
+ diaryelement.Element("diaryshortitem").Element("data").Element("kcal").Value + "kcal";
diary.Add(p);
Debug.WriteLine("Added "+p.name);
diaryprodukte.Add(p);
}
How to read rss feed from here in wp7 app using c#: "http://www.nyc.gov/apps/311/311Today.rss"?
My Xaml code:
<ListBox HorizontalAlignment="Left" Margin="10,10,0,0" Name="listBox1" VerticalAlignment="Top" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Top">
<TextBlock x:Name="titleTxt" Height="30" Text="{Binding Title}" VerticalAlignment="Bottom" />
<TextBlock x:Name="dateTxt" Height="30" Text="{Binding Date}" />
<TextBlock x:Name="descTxt" Height="30" Text="{Binding Desc}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My C# code:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
XDocument xDoc = XDocument.Load("http://www.nyc.gov/apps/311/311Today.rss");
XNamespace content = XNamespace.Get("http://purl.org/rss/1.0/modules/content/");
var items = xDoc.Descendants("item")
.Select(i => new
{
Title = i.Element("title").Value,
Date = DateTime.Parse(i.Element("pubDate").Value),
Desc = i.Element(content + "encoded").Value,
})
.ToArray();
listBox1.ItemsSource = items;
}
using (var wc = new WebClient())
{
XDocument xDoc = XDocument.Parse(wc.DownloadString("http://www.nyc.gov/apps/311/311Today.rss"));
XNamespace content = XNamespace.Get("http://purl.org/rss/1.0/modules/content/");
var items = xDoc.Descendants("item")
.Select(i => new
{
Title = i.Element("title").Value,
Date = DateTime.Parse(i.Element("pubDate").Value),
Desc = i.Element(content + "encoded").Value,
})
.ToArray();
}
A while ago I wrote an entire tutorial covering this topic. Details here:
Building a RSS reader for Windows Phone 7 – Designing the structure
Building a RSS reader for Windows Phone 7 – Developing the functionality