windows phone 8 binding list inside list to the listbox - xaml

How can i bind ranking RankingInfo1 and rankinginfo 2 to the listbox. basically i am having trouble with the three level hierarchy. RankingInfo1 -> RankingInfo -> Ranking.
public class BookInfo
{
private long _BookId = 0;
public long BookId
{
get
{
return _BookId;
}
set
{
_BookId = value;
}
}
private string _BookTitle = string.Empty;
public string BookTitle
{
get
{
return _BookTitle;
}
set
{
_BookTitle = value;
}
}
public List<RankInfo> RankingInfo1 { get; set; }
public List<RankInfo> RankingInfo2 { get; set; }
}
public class RankInfo {
public int? Ranking { get; set; }
public DateTime? WeekDate { get ; set ;}
}
what i have tried but the thing is that i am getting : booklocator.Model.RankInfo as the output.
<ListBox x:Name="lstrankingUSAToday" ItemsSource="{Binding RankingInfo1}" Grid.ColumnSpan="2">
<StackPanel Width="Auto">
<TextBlock Text="Ranked USA Today: "/>
<TextBlock Text="{Binding Ranking}"></TextBlock>
</StackPanel>
</ListBox>

You need to use ItemsControl to bind the list of values. I am showing simple demo try it and let me if you need further help.
XAML
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding BookId}" FontSize="20" />
<TextBlock Text="{Binding BookTitle}" FontSize="20" />
<ItemsControl ItemsSource="{Binding RankingInfo1}" Margin="0 20 0 0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Blue" BorderThickness="2">
<TextBlock Text="{Binding Ranking}" FontSize="20" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding RankingInfo2}" Margin="0 20 0 0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="2">
<TextBlock Text="{Binding Ranking}" FontSize="20" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#
public List<BookInfo> Items { get; set; }
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var _RankingInfo1 = new List<RankInfo>
{
new RankInfo { Ranking = 1, WeekDate = DateTime.Now },
new RankInfo { Ranking = 2, WeekDate = DateTime.Now }
};
var _RankingInfo2 = new List<RankInfo>
{
new RankInfo { Ranking = 10, WeekDate = DateTime.Now.AddDays(-2) },
new RankInfo { Ranking = 20, WeekDate = DateTime.Now.AddDays(-2) }
};
Items = new List<BookInfo>
{
new BookInfo { BookId = 9, BookTitle = "My Book Title", RankingInfo1 = _RankingInfo1, RankingInfo2 = _RankingInfo2 }
};
this.DataContext = this;
}

Related

Saving with SQL

Hi all I have a page that I'm trying to ADD to a list and save it with viewmodel and SQL. but my list is empty Can you tell me where am I wrong??
on my Xaml (Page1):
<Entry Margin="5" Text="{Binding Xname}" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" FontSize="16" x:Name="entry1" Placeholder="Enter X-rays (6 MV)" PlaceholderColor="White" BackgroundColor="Gray"/>
<Button Grid.Column="0"
Grid.Row="2"
FontAttributes="Bold"
Command="{Binding AddXrayCommand}"
Text="Add" />
<ListView Grid.Row="3" Grid.ColumnSpan="2" HasUnevenRows="True" Margin="40"
ItemsSource="{Binding energyX}" SelectedItem="{Binding selecteditemX}"
HorizontalOptions="Start" WidthRequest="150" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="5"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" BackgroundColor="White" Text="{Binding xray}" FontSize="Large" HorizontalTextAlignment="Center" TextColor="Black" WidthRequest="35"/>
<Frame Grid.Row="1" BackgroundColor="Gray"></Frame>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
my Model (Energypage):
public class EnergyX
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string xray { get; set; }
}
And on my EnergyViewModel:
public class EnergyViewModel
{
public SQLiteConnection conn;
public ObservableCollection<EnergyX> energyX { get; set; } = new ObservableCollection<EnergyX>();
public string Xname { get; set; }
public ICommand AddXrayCommand => new Command(AddX);
public SQLiteConnection GetSQLiteConnection()
{
var fileName = "Energys.db";
var documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
var path = Path.Combine(documentPath, fileName);
var connection = new SQLiteConnection(path);
return connection;
}
public void AddX()
{
if (Xname != null && Xname.Length > 0)
{
EnergyX XX = new EnergyX();
XX.xray = Xname;
conn = GetSQLiteConnection();
conn.CreateTable<EnergyX>();
var dataX = conn.Table<EnergyX>();
var resultX = conn.Insert(XX);
energyX = new ObservableCollection<EnergyX>(conn.Table<EnergyX>().ToList());
}
}
}
}
I did bond my page1 to Energyviewmodel, and it works find when I didn't use SQL service, I think my SQL has problem...
I have debug the viewmodel and program run to the end of the Viewmodel but my xaml page list is empty.
this line creates a completely new instance of energyX when your ListView is bound to the old instance
energyX = new ObservableCollection(conn.Table().ToList());
there are two ways you could fix this
option 1, use INotifyPropertyChanged and raise a PropertyChanged event in the setter of energyX
option 2, don't create a new instance of energyX. Instead just add the new item to the existing instance
energyX.Add(XX);

Refresh SemanticZoom ObservableCollection in ViewModel

When using a SemanticZoom control, is there a way to update the ObservableCollection in the ViewModel after a table change? After making changes to the table in SQLite, within the same page (categories.xaml.cs), the SemanticZoom control does not update. Reloading the page from menu navigation does reload the page with the correct data. If the control just took an ObservableCollection as it's items source, the ObservableCollection could just be refreshed. Using a ViewModel was the only code example I could find for the SemanticZoom control. Thanks in advance!
categories.xaml
<Page.DataContext>
<vm:CategoriesViewModel></vm:CategoriesViewModel>
</Page.DataContext>
<Page.Resources>
<CollectionViewSource x:Name="Collection" IsSourceGrouped="true" ItemsPath="Items" Source="{Binding CategoryGroups}" />
</Page.Resources>
<SemanticZoom Name="szCategories" ScrollViewer.ZoomMode="Enabled">
<SemanticZoom.ZoomedOutView>
<GridView ScrollViewer.IsHorizontalScrollChainingEnabled="False">
<GridView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Group.Name }" Foreground="Gray" Margin="5" FontSize="25" />
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</SemanticZoom.ZoomedOutView>
<SemanticZoom.ZoomedInView>
<ListView Name="lvCategories" ItemsSource="{Binding Source={StaticResource Collection}}" Tapped="lvCategories_Tapped">
<ListView.ItemTemplate>
<DataTemplate x:DataType="data:Category">
<StackPanel>
<TextBlock Text="{Binding Title}" Margin="5" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text='{Binding Name}' Foreground="Gray" FontSize="25" Margin="5,5,5,0" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
</SemanticZoom.ZoomedInView>
</SemanticZoom>
categories.xaml.cs
public Categories()
{
this.InitializeComponent();
var collectionGroups = Collection.View.CollectionGroups;
((ListViewBase)this.szCategories.ZoomedOutView).ItemsSource = collectionGroups;
}
CategoriesViewModel.cs
internal class CategoriesViewModel : BindableBase
{
public CategoriesViewModel()
{
CategoryGroups = new ObservableCollection<CategoryDataGroup>(CategoryDataGenerator.GetGroupedData());
}
private ObservableCollection<CategoryDataGroup> _groups;
public ObservableCollection<CategoryDataGroup> CategoryGroups
{
get { return _groups; }
set { SetProperty(ref _groups, value); }
}
}
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
SymanticZoom.cs
internal class CategoryDataGroup
{
public string Name { get; set; }
public List<CategoryData> Items { get; set; }
}
internal class CategoryData
{
public CategoryData(string grp, string title)
{
Grp = grp;
Title = title;
}
public string Grp { get; private set; }
public string Title { get; private set; }
}
internal class CategoryDataGenerator
{
private static List<CategoryData> _data;
public static List<CategoryDataGroup> GetGroupedData()
{
if (_data != null)
_data.Clear();
GenerateData();
return _data.GroupBy(d => d.Grp[0],
(key, items) => new CategoryDataGroup() { Name = key.ToString(), Items = items.ToList() }).ToList();
}
private static void GenerateData()
{
ObservableCollection<Category> ocCategories = new ObservableCollection<Category>();
SQLiteManager.Categories.Select(ocCategories);
_data = new List<CategoryData>();
foreach (var temp in ocCategories)
{
_data.Add(new CategoryData(temp.Name.Substring(0,1), temp.Name));
}
}
}
The zoomed-in view and zoomed-out view should be synchronized, so if a user selects a group in the zoomed-out view, the details of that same group are shown in the zoomed-in view. You can use a CollectionViewSource or add code to synchronize the views.
For more info, see Semantic zoom.
We can use CollectionViewSource control in our page, it provides a data source that adds grouping and current-item support to collection classes. Then we can bind the GridView.ItemSource and ListView.ItemSource to the CollectionViewSource. When we set new data to the CollectionViewSource, the GridView in SemanticZoom.ZoomedOutView and ListView in SemanticZoom.ZoomedInView will be updated.
xmlns:wuxdata="using:Windows.UI.Xaml.Data">
<Page.Resources>
<CollectionViewSource x:Name="ContactsCVS" IsSourceGrouped="True" />
<DataTemplate x:Key="ZoomedInTemplate" x:DataType="data:Contact">
<StackPanel Margin="20,0,0,0">
<TextBlock Text="{x:Bind Name}" />
<TextBlock Text="{x:Bind Position}" TextWrapping="Wrap" HorizontalAlignment="Left" Width="300" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="ZoomedInGroupHeaderTemplate" x:DataType="data:GroupInfoList">
<TextBlock Text="{x:Bind Key}"/>
</DataTemplate>
<DataTemplate x:Key="ZoomedOutTemplate" x:DataType="wuxdata:ICollectionViewGroup">
<TextBlock Text="{x:Bind Group.(data:GroupInfoList.Key)}" TextWrapping="Wrap"/>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<SemanticZoom x:Name="Control1" Height="500">
<SemanticZoom.ZoomedInView>
<GridView ItemsSource="{x:Bind ContactsCVS.View,Mode=OneWay}" ScrollViewer.IsHorizontalScrollChainingEnabled="False" SelectionMode="None"
ItemTemplate="{StaticResource ZoomedInTemplate}">
<GridView.GroupStyle>
<GroupStyle HeaderTemplate="{StaticResource ZoomedInGroupHeaderTemplate}" />
</GridView.GroupStyle>
</GridView>
</SemanticZoom.ZoomedInView>
<SemanticZoom.ZoomedOutView>
<ListView ItemsSource="{x:Bind ContactsCVS.View.CollectionGroups}" SelectionMode="None" ItemTemplate="{StaticResource ZoomedOutTemplate}" />
</SemanticZoom.ZoomedOutView>
</SemanticZoom>
</StackPanel>
</Grid>

How do I self-reference a DataTemplate in UWP XAML Resources?

I've seen something along these lines done with {DynamicResource xyz}on some other SO question, but it doesn't seem to work with UWP. Here's my XAML:
<DataTemplate x:Key="commentTemplate">
<StackPanel>
<Grid Margin="4" Background="#40606060" MinHeight="64">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<StackPanel>
<TextBlock Margin="4" FontSize="14" TextWrapping="WrapWholeWords" Text="{Binding Path=Message, Mode=OneWay}" />
<Image MaxHeight="96" Source="{Binding Path=Image}" HorizontalAlignment="Left" Margin="4" />
</StackPanel>
<StackPanel Background="#18808080" Orientation="Horizontal" Grid.Row="1">
<FontIcon Margin="2,0" Glyph="" />
<TextBlock Margin="2,0" Text="{Binding Path=Score, Mode=OneWay}" />
<Button Content="Reply" Margin="2,0" />
</StackPanel>
</Grid>
<ItemsControl ItemTemplate="{RelativeSource Mode=Self}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" Margin="48" ItemsSource="{Binding Path=Comments}" />
</StackPanel>
</DataTemplate>
I'd like to self-reference the DataTemplate in the ItemsControl's ItemTemplate property. How would I go about replacing it?
Here is something that may work for you. I use this in our POS application - although this is my first attempt at nesting it. The xaml designer complains because of the selector StaticResource reference prior to its declaration, but it works at runtime.
Essentially, I use this to select a different data template based on the class that is bound to the item. In this case, there is only one type, so really we are just using the class type to decide what template to use.
MyModel:
public class MyModel
{
public int Id { get; set; }
public string Desc { get; set; }
public List<MyModel> Children { get; set; }
}
MyTemplateSelector:
public class MyTemplateSelector : DataTemplateSelector
{
public DataTemplate MyModelTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item)
{
if (item is MyModel)
{
return MyModelTemplate;
}
else
{
return null;
}
}
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
return SelectTemplateCore(item);
}
}
My MainPage:
<Page
x:Class="App7.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App7"
xmlns:models="using:App7.Models"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate x:Key="myModelTemplate" x:DataType="models:MyModel">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{x:Bind Path=Desc, Mode=OneWay}" />
<ListView Grid.Row="1" ItemTemplateSelector="{StaticResource selector}" ItemsSource="{x:Bind Path=Children, Mode=OneWay}" />
</Grid>
</DataTemplate>
<local:MyTemplateSelector x:Key="selector" MyModelTemplate="{StaticResource myModelTemplate}" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="lstView" ItemTemplateSelector="{StaticResource selector}" >
</ListView>
</Grid>
</Page>
My code behind:
public sealed partial class MainPage : Page
{
List<MyModel> lst { get; set; }
public MainPage()
{
this.InitializeComponent();
BuildList();
lstView.ItemsSource = lst;
}
private void BuildList()
{
lst = new List<MyModel>();
for (int i = 0; i < 10; i++)
{
MyModel mod = new MyModel();
mod.Id = i;
mod.Desc = "Desc" + i.ToString();
mod.Children = new List<MyModel>();
for (int j = 100; j < 102; j++)
{
MyModel mod2 = new MyModel();
mod2.Id = j;
mod2.Desc = "Desc" + j.ToString();
mod2.Children = new List<MyModel>();
for (int k = 1000; k < 1002; k++)
{
MyModel mod3 = new MyModel();
mod3.Id = k;
mod3.Desc = "Desc" + k.ToString();
mod3.Children = new List<MyModel>();
mod2.Children.Add(mod3);
}
mod.Children.Add(mod2);
}
lst.Add(mod);
}
}
}

windows store app how to get back values from databinded usercontroles

how can i get back values from data binder view elements
am using a list view and data binded it to collection
<ListView.Resources>
<DataTemplate x:Key="DataTemplate1">
<Grid Height="20" Width="100" Background="#FFF5F3F3" Tapped="Grid_Tapped">
<TextBlock Text="{Binding Name}" Foreground="#FF0E0303"/>
<TextBlock Text="{Binding Age}" Foreground="#FF0E0303"/>
</Grid>
</DataTemplate>
now what i want is get the values back at gridtapped event
Try this
<ListView x:Name="lv" IsItemClickEnabled="True" ItemClick="lv_ItemClick_1">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="20" Width="100" Background="#FFF5F3F3">
<TextBlock Text="{Binding Name}" Foreground="#FF0E0303"/>
<TextBlock Text="{Binding Age}" Foreground="#FF0E0303"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
lv.ItemsSource = new List<Person>
{
new Person("Charles", 25),
new Person("Mark", 27),
new Person("John", 22),
};
}
private void lv_ItemClick_1(object sender, ItemClickEventArgs e)
{
var objPerson = (Person)e.ClickedItem;
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}

xaml: Can't get image binding to work

I'm trying to do some databinding, but I can't get the image to show. This is what the xaml looks like:
<ListBox Name="tListBox" Margin="0,0,-12,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<Image Source="{Binding imgUri}" Margin="2" Height="100" Width="100" />
<!--<Image Source="images/weapons/tmp.png" Height="100" Width="100" />-->
<StackPanel Width="311">
<TextBlock Text="{Binding wName}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" />
<TextBlock Text="{Binding price}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is what the codebehind looks like:
public partial class MainPage : PhoneApplicationPage
{
List<Weapon> tList;
List<Weapon> cList;
List<Weapon> eList;
// Constructor
public MainPage()
{
InitializeComponent();
loadData();
}
public void loadData()
{
tList = new List<Weapon>();
tList.Add(new Weapon
{
wName = "Glock 18",
imageUri = "images/weapons/glock18.png",
price = "$400"
});
tList.Add(new Weapon
{
wName = "USP tactical",
imageUri = "images/weapons/usptactical.png",
price = "$500",
});
tListBox.ItemsSource = tList;
}
}
public class Weapon
{
public string wName { get; set; }
public string imageUri { get; set; }
public string price { get; set; }
}
When running this the name and price gets shown, but not the image. The line that is commented out in the xaml works, can anyone please correct what am I doing wrong?
Found the mistake. imgUri in the xaml and imageUri in the codebehind - different variable names. Quite embarrassing ;)