ListBox in C# doesn't show up - c#

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);
}

Related

Filter List view on item click - uwp

I have a list view which shows main subject and optional subject of students selected. Now I want to filter the listview when clicking on each row of it. The filtering should be based on main subject and optional subject. Means filtered rows of listview either contains any of main subject or optional subject.
<ListView x:Name="ItemListView" Width="Auto" Height="Auto" HorizontalAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding StudentName}" TextAlignment="Left" FontSize="20" Width="50"/>
</StackPanel>
<StackPanel>
<TextBlock Text="{Binding MainSub}" FontSize="20" TextAlignment="Center" />
</StackPanel>
<StackPanel>
<TextBlock Text="{Binding OptionalSub}" FontSize="20" TextAlignment="Center" />
</StackPanel>
<StackPanel >
<TextBlock Text="{Binding RollNo}" FontSize="20" TextAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
ItemDetails messageData = new ItemDetails();
ItemListView.ItemsSource = messageData.Collection;
ItemListView.SelectedIndex = 0;
}
public class ItemDetails
{
public ItemDetails()
{
MatchList item;
item = new MatchList();
item.StudentName = "FF";
item.MainSub= selectedSub[0].ToString();//English
item.OptionalSub =selectedSub[1].ToString();//Sanskrit
item.RollNo = 922;
Collection.Add(item);
item = new MatchList();
item.StudentName = "DD";
item.MainSub= selectedSub[0].ToString();//English
item.OptionalSub =selectedSub[2].ToString();//Arabic
item.RollNo = 82;
Collection.Add(item);
item = new MatchList();
item.StudentName = "CC";
item.MainSub= selectedSub[3].ToString();//Science
item.OptionalSub =selectedSub[2].ToString();//Arabic
item.RollNo = 12;
Collection.Add(item);
item = new MatchList();
item.StudentName = "BB";
item.MainSub= selectedSub[3].ToString();//Science
item.OptionalSub =selectedSub[4].ToString();//Moral Science
item.RollNo = 22;
Collection.Add(item);
item = new MatchList();
item.StudentName = "AA";
item.MainSub= selectedSub[0].ToString();//English
item.OptionalSub =selectedSub[1].ToString();//Sanskrit
item.RollNo = 322;
Collection.Add(item);
}
List<MatchList> collection = new List<MatchList>();
public List<MatchList> Collection
{
get
{
return this.collection;
}
}
}
Well it seems several things are not yet complete in this sample code...
First up I suggest you use an ObservableCollection for the actual Collection property - this is needed so that your View will be notified if elements are added or removed from the collection.
Secondly you'll want to hook up a CollectionViewSource to your ListView ItemsSource and set it's Source to the ObservableCollection Collection property.
Last thing to do is then react to the ItemSelected of the ListView to filter out elements from the ObservableCollection. It should be reflected back to the ListView thanks to Data Binding.

Multi level data Binding in Windows Phone 8

I am a beginner in Windows phone programming.
I want to bind the data from API to my XAML elements using that Binding Attributes. Please let me know how can we bind multilevel classes objects in it.
Here's my scenario.
List<Sample> SearchResult = new List<Sample>()
{
new Sample(){
Name="ABC",
modelProperty = new SampleDetail(){
articleNo="1", videoURL = "https://www.youtube.com/watch?v=abc",
colors = new List<ColorsDemo>(){
new ColorsDemo {
Name = "Red",
colorProperty= new ColorDemoProperty{ name = "ABC",article_no = "Art1",
image = new Uri("http://img.youtube.com/vi/e60E99tUdxs/default.jpg",UriKind.RelativeOrAbsolute)
}
}
}
}
}
And now, I want to bind the Name of ColorsDemo class into my textblock. See what I have done to bind in XAML like this:
<TextBlock x:Name="PName" Grid.Row="0" Margin="100,0,0,0" Tap="ProductName_Tap" HorizontalAlignment="Center" VerticalAlignment="Center" Width="350" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=modelProperty.colors.Name}" FontSize="30"></TextBlock>
From your code, i see that colors is a List of ColorDemo objects. So when you say {Binding Path=modelProperty.colors.Name}it does not tell which list item to bind to. The correct usage should be {Binding Path=modelProperty.colors[0].Name}. This tells the control to bind to the name of the first color item (as index is 0).
To bind all the colors. You should use a Listview and bind the colors in it. So you should be able to do something like this.
<ListView ItemSource={Binding Path=modelProperty.colors}>
<ListView.ItemTemplate>
<TextBlock x:Name="PName" Grid.Row="0" Margin="100,0,0,0" Tap="ProductName_Tap" HorizontalAlignment="Center" VerticalAlignment="Center" Width="350" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=Name}" FontSize="30"></TextBlock>
</ListView.ItemTemplate>
</ListView>

how to bind tweetinvi xaml listview?

I'am new to tweetinvi, and now i'm stuck with databinding. it's doable to retrieve tweets and i can show up the last one in a TextBlock in my XAML. but now i like to have it in a list or gridview.
code to retrieve tweets
var homeTimelineTweets = authenticatedUser.GetHomeTimeline();
foreach (var tweet in homeTimelineTweets)
{
textBlock.Text = tweet.Text;
//textBlock.Text = tweet.CreatedBy.ScreenName;
//textBlock.Text = tweet.CreatedBy.Name + ", " +tweet.Text;
//textBlock.Text = tweet.Text;
}
Code for Xaml
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="textBlock"
HorizontalAlignment="Left"
TextWrapping="Wrap"
Text="TextBlock"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
i know i have to set x:bind and x:data ... but i can figure out how?

Binding data in stackpanel

I use WPF and c#.
I have an issue regarding binding and visibility.
I have a tree which is bound to obsCol1. Then I have a form in a grid whose datacontext is set to `
DataContext="{Binding ElementName=tree, Path=SelectedItem}">`
Inside that form I have 3 identical subforms if you will. Each of the 3 subforms is a groupbox inside of which is a horizontal stack panel in which there is a label textbox label textbox button.
<GroupBox Grid.Column="3" Grid.Row="8" Grid.ColumnSpan="3">
<GroupBox.Header>Reklama 1</GroupBox.Header>
<StackPanel Name="Rek1" DataContext="Reklame" Orientation="Horizontal">
<Label Grid.Column="3" Grid.Row="10" HorizontalAlignment="Right" VerticalAlignment="Top">Datum post/zam</Label>
<xctk:DateTimePicker x:Name="dtReklama1"
Grid.Row="10"
Grid.Column="4"
Height="25"
Margin="3"
Padding="3"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Width="150" Value="{Binding Path=Opr_brendiranje}"/>
<Label Grid.Column="3" Grid.Row="8" HorizontalAlignment="Right" VerticalAlignment="Top">Dimenzija</Label>
<extToolkit:WatermarkTextBox x:Name="Reklama" Grid.Row="8"
Grid.Column="4"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Width="100"
Height="25"
Padding="3"
Margin="3"
AcceptsReturn="True"
Validation.ErrorTemplate="{StaticResource ValidationTemplate}"
Validation.Error="Validation_Error">
<extToolkit:WatermarkTextBox.Watermark>
<TextBox Text="Reklama" Margin="4,2,2,0" FontWeight="Regular" Foreground="Silver" BorderThickness="0"/>
</extToolkit:WatermarkTextBox.Watermark>
<extToolkit:WatermarkTextBox.Text>
<Binding Path="RekDimenzije" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True"/>
</extToolkit:WatermarkTextBox.Text>
</extToolkit:WatermarkTextBox>
<Button Grid.Column="5" Grid.Row="9" Height="20" Width="15" Click="Dodaj_Reklamu" VerticalAlignment="Top" FontWeight="Bold" Margin="5" >+</Button>
</StackPanel>
</GroupBox>
So now I need to bind this but the issue is that these subforms use a different class from the form itself. They are an entity in and of itself. So I was wondering if there was any way to bind them independently somehow like itemsource the groupbox or the stack panel or soemthing. I tried using itemscontrol and binding to it but that did not work it would bind the itemsource but if the itemsource was empty the control would dissapear therefore not allowing the user to add it.
Any help would be appreciated.
Update:
Ok so I have a single usercontrol.
On the left side is a tree that uses a HierarchicalDataTemplate that is bound to 2 different classes one of which OrgSredstva is OrgClass with Sredstva class contained within.
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Org_Sredstva}">
<HierarchicalDataTemplate.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="Focusable" Value="False"/>
</Style>
</HierarchicalDataTemplate.ItemContainerStyle>
<TextBlock Text="{Binding Path=Organizacije_Naziv}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Ossr_Naziv}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
This all works as complicated as it sounds the tree works fine.
On the right side is a grid that like i described above has datacontext set to whatever is selected in the tree. I need this so that when the selection changes in the tree the form changes with it. The issue is that neither of the classes the tree is bound to is the class the form should be bound to. So the grid can't find the data because the textbox bindings aren't in that observable collection but another one. The way I solved this is to bind every textbox.text property in codebehind so
public void OdabranoDrvo()
{
OdabranaOrg = this.View.tree.SelectedItem as Organizacije;
if (OdabranaOrg != null)
{
string orgId = OdabranaOrg.Organizacije_Sifra;
IEnumerable<Opremljenost> odabranaOpr = from fn in _oprema
where fn.Opr_org_sifra == orgId
select fn;
var ob = new ObservableCollection<Opremljenost>(odabranaOpr);
if (ob.Count > 0)
{
foreach (Opremljenost opr in odabranaOpr)
{
this.View.Povrsina.Text = opr.Opr_Povrsina.ToString();
this.View.RadnoVrijeme.Text = opr.Opr_RadnoVrijeme;
if (opr.Opr_Vlasnik == 1)
{
this.View.LutRad.IsChecked = true;
this.View.ImeVlasnika.IsReadOnly = true;
}
else
{
this.View.LutRad.IsChecked = false;
this.View.ImeVlasnika.IsReadOnly = false;
}
this.View.ImeVlasnika.Text = opr.Opr_ime_vlasnik;
if (opr.Opr_brojilo == 1)
{
this.View.Brojilo.IsChecked = true;
}
else
{
this.View.Brojilo.IsChecked = false;
}
if (opr.Opr_ventilacija == 1)
{
this.View.Ventilacija.IsChecked = true;
}
else
{
this.View.Ventilacija.IsChecked = false;
}
this.View.dtBrendiranje.Value = opr.Opr_brendiranje;
this.View.dtKrecenje.Value = opr.Opr_krecenje;
this.View.Napomena.Text = opr.Opr_napomena;
this.View.BrojAparata.Text = opr.Opr_broj_aparata.ToString();
this.View.BrojRuleta.Text = opr.Opr_broj_ruleta.ToString();
this.View.UkupanBrojKlima.Text = opr.Opr_uku_br_klima.ToString();
this.View.BrojKlimaLutrija.Text = opr.Opr_br_kl_lut.ToString();
this.View.UkupanBrojTv.Text = opr.Opr_uku_broj_tv.ToString();
this.View.BrojTvLutrija.Text = opr.Opr_broj_tv_lut.ToString();
this.View.BrojTvPartneri.Text = opr.Opr_broj_tv_partneri.ToString();
this.View.StrujnaSnaga.Text = opr.Opr_struja_ang_snaga.ToString();
_slikeOpr = Ap.GlavniRepository.UcitajSlikeZaOpremu(opr.Opr_Id);
this.View.Thumbnails.ItemsSource = _slikeOpr;
_reklame = Ap.GlavniRepository.UcitajReklameZaOpremu(opr.Opr_Id);
int i = _reklame.Count();
if (i == 2)
{
this.View.Rek2.Visibility = Visibility.Visible;
this.View.Rek3.Visibility = Visibility.Collapsed;
}
else if (i == 3)
{
this.View.Rek2.Visibility = Visibility.Visible;
this.View.Rek3.Visibility = Visibility.Visible;
}
else
{
this.View.Rek2.Visibility = Visibility.Collapsed;
this.View.Rek3.Visibility = Visibility.Collapsed;
}
this.View.Reklame.DataContext = _reklame;
}
}
else
{
this.View.Povrsina.Text = "0";
this.View.RadnoVrijeme.Text = String.Empty;
this.View.LutRad.IsChecked=false;
this.View.ImeVlasnika.Text = String.Empty;
this.View.Brojilo.IsChecked = false;
this.View.Ventilacija.IsChecked = false;
this.View.dtBrendiranje.Value = DateTime.Now;
this.View.dtKrecenje.Value = DateTime.Now;
this.View.Napomena.Text = String.Empty;
this.View.BrojAparata.Text = "0";
this.View.BrojRuleta.Text = "0";
this.View.UkupanBrojKlima.Text = "0";
this.View.BrojKlimaLutrija.Text = "0";
this.View.UkupanBrojTv.Text = "0";
this.View.BrojTvLutrija.Text = "0";
this.View.BrojTvPartneri.Text = "0";
this.View.StrujnaSnaga.Text = "0";
this.View.Thumbnails.ItemsSource = null;
this.View.Rek2.Visibility = Visibility.Collapsed;
this.View.Rek3.Visibility=Visibility.Collapsed;
}
}
}
The original question i resolved by creating a new grid inside my preexisting grid and just setting the data context for that inner grid to what I needed it to be. Now I find that all the bindings seem to work at least on reading from database, haven't tested inserting into database yet.
I realise this is all very ugly but I couldn't figure out a way to actually bind it while it still working as it should...

I can't display the result of my rss reader

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.

Categories