Data binding in ListBox on Windows Phone 8 - c#

I'm new to Windows Phone 8. I have a list of data from a server in this form:
RootObject json = JsonConvert.DeserializeObject<RootObject>(await serverData);
mylist.ItemsSource = json.friends;
public class Friend
{
public string first_name { get; set; }
public string last_name { get; set; }
public string place { get; set; }
public string going { get; set; }
public string thumbnail { get; set; }
}
public class RootObject
{
public List<Friend> friends { get; set; }
}
I want to display that data in a ListBox in the UI:
<ListBox x:Name="mylist" Margin="10,0,30,0" Height="486" Width="404" FontSize="20">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Margin="10,0,10,8">
<TextBlock Text="{Binding first_name }" TextWrapping="Wrap" FontSize="18" />
<TextBlock Text="{Binding last_name }" TextWrapping="Wrap" FontSize="18" />
<TextBlock Text="{Binding place }" TextWrapping="Wrap" FontSize="18" />
<TextBlock Text="{Binding going }" TextWrapping="Wrap" FontSize="18" />
<TextBlock Text="{Binding thumbnail }" TextWrapping="Wrap" FontSize="18" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
that is a working version

The ItemsSource on the ListBox should be bound to friends, like this:
<ListBox ItemsSource="{Binding friends}" Margin="10,0,30,0" Height="486" Width="404" FontSize="20">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Margin="10,0,10,8">
<TextBlock Text="{Binding first_name }" TextWrapping="Wrap" FontSize="18" />
<TextBlock Text="{Binding first_name }" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And also if you haven't done it already, you need to set the DataContext for the page after you downloaded the data, like this (assuming you do the downloading in the code-behind file of a page, e.g. MainPage.xaml.cs):
RootObject json = JsonConvert.DeserializeObject<RootObject>(await serverData);
this.DataContext = json;

Related

How to make the SelectedItem in Combobox(customize DataTemplate) shows only specific property of the item

I have a ComboBox that shows a list of information:
NameOfEstablishment
BIN
Owner
BusinessAddress
...appearing like so:
Code:
<ComboBox x:Name="BploList"
Text="{Binding Search}"
SelectedItem="{Binding SearchSelected}"
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="2"
FontSize="16"
materialDesign:HintAssist.Hint="Search"
Margin="5 5 65 5"
IsEditable="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding NameOfEstablishment}" FontSize="12" Foreground="#D8AC6A"
TextWrapping="Wrap" MaxWidth="250" />
<TextBlock Text="{Binding BIN}" FontSize="11" TextWrapping="Wrap" MaxWidth="250" />
<TextBlock Text="{Binding Owner}" FontSize="11" TextWrapping="Wrap" MaxWidth="250" />
<TextBlock Text="{Binding BusinessAddress}" FontSize="11" TextWrapping="Wrap" MaxWidth="250" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
Problem
SelectedItem should show the NameOfEstablishment value only but it instead shows as the full object:
As for Source of ComboBox
private BindingList<BPLOSearchModel> _bploList;
public BindingList<BPLOSearchModel> BploList
{
get { return _bploList; }
set
{
_bploList = value;
NotifyOfPropertyChange(() => BploList);
}
}
Properties of BPLOSearchModel
public class BPLOSearchModel
{
public string BIN { get; set; }
public string NameOfEstablishment { get; set; }
public string BusinessAddress { get; set; }
public string Owner { get; set; }
}
As for SearchSelected
private string _searchSelected;
public string SearchSelected
{
get { return _searchSelected; }
set
{
_searchSelected = value;
NotifyOfPropertyChange(() => SearchSelected);
}
}
This is exactly what SelectedValuePath is for. It is used to
get or set the path that is used to get the SelectedValue of the SelectedItem
In your case, set it like
<ComboBox ... SelectedValuePath="NameOfEstablishment" ... />
Note that there is also a nice How to at Microsoft.

wpf help binding data to controls in TabControl

So I have a TabControl with two TabItems, each TabItem has the same controls on it (8 TextBlocks) and will display data under the same bindings as their counterparts on the other TabItem.
The xaml and cs code that I have is below, but when I try execute it I get this error.
Items collection must be empty before using ItemsSource.
XAML for TabItem Structure
<TabControl Name="tbcIndividualStats" HorizontalAlignment="Left" Height="652" VerticalAlignment="Top" Width="1338" ItemsSouce="{Binding tabcontrolitems}">
<!--Template for all tabs (idea is to have them dynamically created eventually)-->
<!--Content template-->
<TabControl.ContentTemplate>
<DataTemplate>
<Grid>
<!--Border just holds the stuff-->
<Border BorderBrush="#FF53535B" BorderThickness="3" HorizontalAlignment="Left" Height="452" VerticalAlignment="Top" Width="520" Margin="10,135,0,0">
<StackPanel Margin="0,0,-1,0">
<TextBlock Name="txtVenue" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding Venue}" />
<TextBlock Name="txtTopSpeed" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TopSpeed}" />
<TextBlock Name="txtDistRun" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding DistRun}" />
<TextBlock Name="txtTimeLow" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeLow}" />
<TextBlock Name="txtTimeMed" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeMed}" />
<TextBlock Name="txtTimeHigh" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeHigh}" />
<TextBlock Name="txtTimeSprint" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeSprint}" />
<TextBlock Name="txtSprintDist" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding SprintDist}" />
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</TabControl.ContentTemplate>
<!--Item Template-->
<TabControl.ItemTemplate>
<DataTemplate>
<Grid>
<!--Border just holds the stuff-->
<Border BorderBrush="#FF53535B" BorderThickness="3" HorizontalAlignment="Left" Height="452" VerticalAlignment="Top" Width="520" Margin="10,135,0,0">
<StackPanel Margin="0,0,-1,0">
<TextBlock Name="txtVenue" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding Venue}" />
<TextBlock Name="txtTopSpeed" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TopSpeed}" />
<TextBlock Name="txtDistRun" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding DistRun}" />
<TextBlock Name="txtTimeLow" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeLow}" />
<TextBlock Name="txtTimeMed" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeMed}" />
<TextBlock Name="txtTimeHigh" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeHigh}" />
<TextBlock Name="txtTimeSprint" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeSprint}" />
<TextBlock Name="txtSprintDist" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding SprintDist}" />
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</TabControl.ItemTemplate>
<TabItem Header="PlayerName" Background="Transparent" />
<TabItem Header="PlayerName2" Background="Transparent" />
</TabControl>
C# for Binding Data
public class TabItemContent
{
public string Venue { get; set; }
public string TopSpeed { get; set; }
public string DistRun { get; set; }
public string TimeLow { get; set; }
public string TimeMed { get; set; }
public string TimeHigh { get; set; }
public string TimeSprint { get; set; }
public string DistSprint { get; set; }
}
public void foo()
{
//All one line of code
//FileLoadData is a List of another class where all my data is stored
var tabitemcontents = new List<TabItemContent> { new TabItemContent { Venue = FileLoadData[0].Venue, TopSpeed = FileLoadData[0].TopSpeed.ToString(), DistRun = FileLoadData[0].TotalDistance.ToString(), TimeLow = FileLoadData[0].TimeLow.ToString(),
TimeMed = FileLoadData[0].TimeMed.ToString(), TimeHigh = FileLoadData[0].TimeHigh.ToString(), TimeSprint = FileLoadData[0].TimeSprint.ToString(), DistSprint = "null"},
new TabItemContent { Venue = FileLoadData[1].Venue, TopSpeed = FileLoadData[1].TopSpeed.ToString(), DistRun = FileLoadData[1].TotalDistance.ToString(), TimeLow = FileLoadData[1].TimeLow.ToString(),
TimeMed = FileLoadData[1].TimeMed.ToString(), TimeHigh = FileLoadData[1].TimeHigh.ToString(), TimeSprint = FileLoadData[1].TimeSprint.ToString(), DistSprint = "null"}};
//Error here, supposed to add to the TabItems
tbcIndividualStats.ItemsSource = tabitemcontents;
}
I've been looking for a solution for ages and I can't get one to work. I just need to bind that data from FileLoadData[0] and FileLoadData[1] to the two TabItems respectivly.
I would adopt a different strategy:
Add to your model, the name that you want to show in the Header of the Tabitem:
public class TabItemContent
{
public string PlayerName {get; set;} // New Property for the Tabitem Header
public string Venue { get; set; }
public string TopSpeed { get; set; }
public string DistRun { get; set; }
public string TimeLow { get; set; }
public string TimeMed { get; set; }
public string TimeHigh { get; set; }
public string TimeSprint { get; set; }
public string DistSprint { get; set; }
}
Then i'd change the Xaml considering this new attribute:
<TabControl Name="tbcIndividualStats" HorizontalAlignment="Left" Height="652" VerticalAlignment="Top" Width="1338">
<!--Template for all tabs (idea is to have them dynamically created eventually)-->
<!--Content template-->
<TabControl.ContentTemplate>
<DataTemplate>
<Grid>
<!--Border just holds the stuff-->
<Border BorderBrush="#FF53535B" BorderThickness="3" HorizontalAlignment="Left" Height="452" VerticalAlignment="Top" Width="520" Margin="10,135,0,0">
<StackPanel Margin="0,0,-1,0">
<TextBlock Name="txtVenue" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding Venue}" />
<TextBlock Name="txtTopSpeed" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TopSpeed}" />
<TextBlock Name="txtDistRun" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding DistRun}" />
<TextBlock Name="txtTimeLow" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeLow}" />
<TextBlock Name="txtTimeMed" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeMed}" />
<TextBlock Name="txtTimeHigh" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeHigh}" />
<TextBlock Name="txtTimeSprint" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding TimeSprint}" />
<TextBlock Name="txtSprintDist" Margin="10,7" FontSize="30" Foreground="White" Text="{Binding SprintDist}" />
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</TabControl.ContentTemplate>
<!--Item Template-->
<TabControl.ItemTemplate>
<DataTemplate>
<Border>
<Textblock = Text="{Binding PlayerName}"/>
</Border>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
EDIT: the item template is the template for the tabitem button and content template is for its content. Some references here: TabItem.ItemTemplate vs TabItem.ContentTemplate
I've also removed the two TabItem defined inside TabControl.
Remember also to set the ItemsSource -> if you set it in code-behind, remove this line: ItemsSouce="{Binding tabcontrolitems}".
Remove these <TabItem> elements from the XAML:
<TabItem Header="PlayerName" Background="Transparent" />
<TabItem Header="PlayerName2" Background="Transparent" />
You can't both add individual items to the TabControl and use an ItemsSource. It's one way or the other.

How binding my ListBox correctly

My Windows Phone app, have a ListBox populated from a collection produtos. This collection received values from a JSON.
In my ListBox, I "binding" all values from JSON (quantidade, descricao, valor_preco_a, codigo), and a another value (unidade) that it should be produtos.quantidade * produtos.valor_preco_a.
My ListBox:
<controls:PivotItem Header="Consulta" Name="consultaCartao">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ListBox Name="List2" ItemsSource="{Binding produtosCartao}" HorizontalContentAlignment="Stretch" Grid.ColumnSpan="3" Margin="0,182,-66,0" Visibility="Collapsed">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432" Height="Auto">
<StackPanel.Background>
<SolidColorBrush Color="#FFE8FF00" Opacity="0.2"/>
</StackPanel.Background>
<TextBlock Grid.Column="0" Text="{Binding descricao}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Grid.Column="3" TextWrapping="Wrap" Style="{StaticResource PhoneTextSubtleStyle}" Margin="20,5,12,0">
<Run Text="{Binding quantidade}" />
<Run Text="{Binding unidade}" />
</TextBlock>
<TextBlock Grid.Column="3" Text="{Binding valor, ConverterCulture=pt-BR, StringFormat=C2}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" Margin="300,-30,12,0"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I trying with this code:
public ObservableCollection<produtos> produtosCartao { get; set; }
public class produtos
{
public double quantidade { get; set; }
public string descricao { get; set; }
public double valor_preco_a { get; set; }
public string codigo { get; set; }
public string unidade { get; set; }
public double valor { get; set; }
}
void webClient_DownloadStringCompletedProdutos(object sender, DownloadStringCompletedEventArgs e)
{
produtos produto = new produtos();
produto.valor = produto.valor_preco_a * produto.quantidade;
}
In order to use data binding en XAML, you have to set your DataContext property in your listbox.
DataContext property is an object where the xaml engine looks in order to find values that are binded.
You should take a look to this

DataContext Gridview within Stack Panel in XAML Windows Phone 8

I'm trying to data bind a collection ("Dashboard") that contains a ObservableCollection property.
I have managed to databind the dashboard class without any issues. I cant however work out how to databind to the Release collection that is contained within the dashboard class.
The issue seems to be on the GridView which is databound to the Releases property of the Dashboard class. The Stack Panel around the GridView is working correctly.
The classes
public class Dashboard
{
public Dashboard(String id, String projectName)
{
this.Id = id;
this.ProjectName = projectName;
this.Releases = new ObservableCollection<Release>();
}
public string Id { get; private set; }
public string ProjectName { get; private set; }
public ObservableCollection<Release> Releases { get; private set; }
public override string ToString()
{
return this.ProjectName;
}
}
public class Release
{
public Release(string environmentName, string releaseVersion, string state, string releaseDate)
{
EnvironmentName = environmentName;
ReleaseVersion = releaseVersion;
State = state;
ReleaseDate = releaseDate;
}
public string EnvironmentName { get; private set; }
public string ReleaseVersion { get; private set; }
public string State { get; private set; }
public string ReleaseDate { get; private set; }
}
The XAML
<HubSection x:Uid="Dashboard" x:Name="Dashboard" Header="Dashboard" DataContext="{Binding Dashboard}">
<DataTemplate>
<GridView x:Uid="DashboardGrid" x:Name="DashboardGrid" ItemsSource="{Binding}" ItemTemplate="{StaticResource Standard200x180TileItemTemplate}" >
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>
</DataTemplate>
</HubSection>
The data template
<DataTemplate x:Key="Standard200x180TileItemTemplate">
<StackPanel DataContext="{Binding}" >
<TextBlock Text="{Binding ProjectName}" Grid.Column="0" Style="{ThemeResource BaseTextBlockStyle}" Typography.Capitals="SmallCaps" Grid.Row="0" IsTextScaleFactorEnabled="False"/>
<GridView Grid.Row="1" DataContext="{Binding Releases}">
<TextBlock Text="{Binding EnvironmentName}" />
<TextBlock Text="{Binding ReleaseVersion}" />
<TextBlock>hello</TextBlock>
<Border Background="#FF0CB90C" Height="110" Width="110" HorizontalAlignment="Left" Margin="0,0,10,0">
</Border>
</GridView>
</StackPanel>
</DataTemplate>
Set ItemsSource of GridView not DataContext and then use another DataTemplate
<StackPanel>
<TextBlock Text="{Binding ProjectName}" Grid.Column="0" Style="{ThemeResource BaseTextBlockStyle}" Typography.Capitals="SmallCaps" Grid.Row="0" IsTextScaleFactorEnabled="False"/>
<GridView Grid.Row="1" ItemsSource="{Binding Releases}">
<GridView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding EnvironmentName}" />
<TextBlock Text="{Binding ReleaseVersion}" />
<TextBlock>hello</TextBlock>
<Border Background="#FF0CB90C" Height="110" Width="110" HorizontalAlignment="Left" Margin="0,0,10,0">
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</StackPanel>

Binding Error in my windows phone 8 project

Well I am trying to do a simple binding in a Long list but the emulator is throwing a debug Exception in
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
I would paste my code below
My model class is
public class CommentView
{
public string ID { get; set; }
public string IsApproved { get; set; }
public string PostersComment { get; set; }
public string Name { get; set; } //Note that this is the name of the Jizuser
public string PostedDate { get; set; }
public string PostedTime { get; set; }
}
I am doing my binding from the xaml csharp code. so the script is pasted below
List<CommentView> commenterContainer = new List<CommentView>();
commenterContainer.Add(new CommentView() { Name ="FEMI", IsApproved="True", ID="1", PostedDate="2/3/2014", PostedTime="01:02:2011", PostersComment= "Me" });
commenterlist.ItemsSource = commenterContainer;
This is the longlist item. how I crafted the dataItem template
<phone:LongListSelector Margin="3" x:Name="commenterlist" SelectionChanged ="Bloglist_SelectionChanged" Grid.Row="6"
Background="White">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="#4063A9">
<StackPanel Margin="10,10,10,10" Orientation="Vertical" >
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="{Binding ID}" Visibility="Collapsed"/>
<Image Source="/Assets/profile.jpg"/>
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Margin="12,20,0,0" Style="{StaticResource PhoneTextNormalStyle}" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="#4063A9"/>
</StackPanel>
<TextBlock Text="{Binding PostersComment}" Margin="12,-6,0,0" Style="{StaticResource PhoneTextSubtleStyle}" TextWrapping="Wrap" />
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="{Binding PostedDate}" />
<TextBlock x:Name="{Binding PostedTime}" />
<TextBlock x:Name="{Binding IsApproved}" Visibility="Collapsed"/>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
Problem was from the LongListSelector
Recreating the LongListSelector Solves the issue. I did this and it works fine

Categories

Resources