Get ListView item's details on ItemClick() event - c#

I've tried searching around here and on microsoft docs but I can't find a solution to my specific query, as mainly I've seen posts about how to do things on itemclick rather than retrieve data.
I'm currently using an API, which sends a JSON request that I deserialize into 2 partial classes, where I use a foreach loop to add new items to the ListView. You can see the classes here:
public partial class GameListObject
{
[JsonPropertyName("id")]
public long GameID { get; set; }
[JsonPropertyName("name")]
public string GameName { get; set; }
[JsonPropertyName("release_dates")]
public ObservableCollection<ReleaseDate> ReleaseDates { get; set; }
}
public partial class ReleaseDate
{
[JsonPropertyName("id")]
public long Id { get; set; }
[JsonPropertyName("human")]
public string Human { get; set; }
}
And the request, deserialization and adding to the ListView here:
//On search box content change
private async void gamehub_search_TextChanged(object sender, TextChangedEventArgs e)
{
var SearchQuery = gamehub_search.Text;
try
{
// Construct the HttpClient and Uri
HttpClient httpClient = new HttpClient();
Uri uri = new Uri("https://api.igdb.com/v4/games");
httpClient.DefaultRequestHeaders.Add("Client-ID", App.GlobalClientidIGDB);
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + App.GlobalAccessIGDB);
//Debug.WriteLine("Request Headers: ");
// Construct the JSON to post
HttpStringContent content = new HttpStringContent($"search \"{SearchQuery}\"; fields name,release_dates.human;");
Debug.WriteLine("Request Contents: " + content);
// Post the JSON and wait for a response
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
uri,
content);
// Make sure the post succeeded, and write out the response
httpResponseMessage.EnsureSuccessStatusCode();
var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
Debug.WriteLine("Request Response: " + httpResponseBody);
//Deserialise the return output into game id, game name and release date
List<GameListObject> gamelistobjects = JsonSerializer.Deserialize<List<GameListObject>>(httpResponseBody);
ObservableCollection<GameListObject> dataList = new ObservableCollection<GameListObject>(gamelistobjects);
ObservableCollection<GameListObject> GameList = new ObservableCollection<GameListObject>();
foreach (var item in dataList)
{
Debug.WriteLine($"id: {item.GameID}");
Debug.WriteLine($"name: {item.GameName}");
GameListObject add = new GameListObject() { GameID = item.GameID, GameName = item.GameName };
GameList.Add(add);
if (item.ReleaseDates != null)
{
foreach (var date in item.ReleaseDates)
{
Debug.WriteLine($"releaseDate: {date.Human}");
}
}
}
gamehub_list.ItemsSource = GameList;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
Now I have set an gamehub_list_ItemClick method which runs when an item within the ListView is pressed. I would like to retrieve the GameID that's present in that item because I'll need that for another page which the user gets redirected to so that I know what game I must request data for. However, I've tried finding the index of the item and using the member names of the class to retrieve it but I can't seem to get it working.
The ItemClick method currently is:
private void gamehub_list_ItemClick(object sender, ItemClickEventArgs e) //When an item in List View is pressed
{
string clickedItemText = e.ClickedItem.ToString();
Debug.WriteLine("Click Item text: " + clickedItemText);
}
When I tried to get the index of the item, it always returned as -1 and for the current clickedItemText it returns "Click Item text: ReviewR.GameHubs+GameListObject".
My xaml with the ListView:
<ListView x:Name="gamehub_list" SelectionMode="None" IsItemClickEnabled="True" ItemClick="gamehub_list_ItemClick" Margin="30,140,44,30" BorderThickness="5" BorderBrush="Black" Background="Gray" RequestedTheme="Dark" Visibility="Collapsed">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel>
<TextBlock Text="{Binding GameID}"></TextBlock>
<TextBlock Text="{Binding GameName}"></TextBlock>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Click Item text: ReviewR.GameHubs+GameListObject
The problem is ClickedItem is object type, if you pass it to string directly, it will return text like you mentioned above.
For this scenario, you need unbox ClickedItem.
var clickedItem = e.ClickedItem as GameListObject
Debug.WriteLine("Click Item text: " + clickedItem.GameID );

Related

C# Xamarin Forms Populating CollectionView from ViewModel is always null

I am trying to populate a collection view from a ViewModel, however when I try to bind the data to the collection view, the ViewModel is null.
xaml.cs file
ObservableCollection<ReportsClass> newKidList = new ObservableCollection<ReportsClass>();
public ReportsViewModel viewmodel { get; set; }
public ReportsPage()
{
InitializeComponent();
viewmodel = new ReportsViewModel();
this.BindingContext = viewmodel;
PreviousDateRange.CornerRadius = 20;
NextDateRange.CornerRadius = 20;
DateTime firstDate = currentDate.StartOfWeek(DayOfWeek.Sunday);
DateTime secondDate = currentDate.AddDays(7).StartOfWeek(DayOfWeek.Saturday);
DateRange.Text = firstDate.ToString("MMMM d") + " - " + secondDate.ToString("MMMM d");
Kids.SetBinding(ItemsView.ItemsSourceProperty, nameof(viewmodel.kids));
}
Here is my view model
public class ReportsViewModel
{
public ObservableCollection<ReportsClass> kids { get; set; }
FirebaseStorageHelper firebaseStorageHelper = new FirebaseStorageHelper();
WebServiceClass webServiceClass = new WebServiceClass();
DateTime currentDate = DateTime.Now;
public ReportsViewModel()
{
GetKids();
}
public async void GetKids()
{
var parentId = await SecureStorage.GetAsync("parentid");
kids = await webServiceClass.Reports(Convert.ToInt32(parentId), currentDate.StartOfWeek(DayOfWeek.Sunday), currentDate.AddDays(7).StartOfWeek(DayOfWeek.Saturday));
}
}
And here is the method that gets the data for the view model
public async Task<ObservableCollection<ReportsClass>> Reports(int parentid, DateTime startDate, DateTime endDate)
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("parentid", parentid.ToString()),
new KeyValuePair<string, string>("startDate", startDate.ToString("yyyy-MM-dd H:mm:ss")),
new KeyValuePair<string, string>("endDate", endDate.ToString("yyyy-MM-dd"))
});
var response = await client.PostAsync(string.Format("https://example.com/api/index.php?action=reports"), content);
var responseString = await response.Content.ReadAsStringAsync();
ObservableCollection<ReportsClass> items = JsonConvert.DeserializeObject<ObservableCollection<ReportsClass>>(responseString);
return items;
}
What am I doing wrong? The purpose of me doing it this way is so I can update an item in the collectionview
Here is my ReportsClass
public class ReportsClass
{
public ReportsClass(string firstName)
{
first_name = firstName;
}
public string first_name { get; set; }
}
OPTION A:
Fix the syntax of Kids.SetBinding, to not get null. Refer to the CLASS ReportsViewModel, not to the INSTANCE viewmodel:
Kids.SetBinding(ItemsView.ItemsSourceProperty, nameof(ReportsViewModel.kids));
The kids still won't appear in list. To fix, kids needs OnPropertyChanged:
public ObservableCollection<ItemModel> kids {
get => _kids;
set {
_kids = value;
OnPropertyChanged();
}
}
private ObservableCollection<ItemModel> _kids;
See the other code in Option B. Adapt as desired.
When you need XAML to see a DYNAMIC change, you need OnPropertyChanged. This is an implementation of INotifyPropertyChanged. Add this call to properties (that XAML binds to) of ReportsClass:
// Inheriting from `BindableObject` is one way to obtain OnPropertyChanged method.
public class ReportsClass : Xamarin.Forms.BindableObject
{
public ReportsClass(string firstName)
{
first_name = firstName;
}
public string first_name {
get => _first_name;
set {
_first_name = value;
// This tells XAML there was a change.
// Makes "{Binding first_name}" work dynamically.
OnPropertyChanged();
}
}
private string _first_name;
}
OPTION B:
Didn't find an answer anywhere that does everything correctly, so here is a complete sample, for future reference:
Remove Kids.SetBinding(...). (It can be fixed as shown in OPTION A, but its easier to get it correct in XAML, so below I show it in XAML.)
Bindings from Page to VM. See xaml below.
Create ObservableCollection with setter that does OnPropertyChanged. This informs XAML when the list is ready, so page updates. (This is an implementation of INotifyPropertyChanged, as Jason mentioned.)
Use Device.BeginInvokeOnMainThread(async () to create an async context, that is queued to run after constructor returns. (This fixes the issue Jason mentioned, which is that a constructor isn't an async context, so should not DIRECTLY call an async method such as QueryItemsAsync, or your GetKids.) This is more reliable.
PageWithQueryData.xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestXFUWP.PageWithQueryData">
<ContentPage.Content>
<StackLayout>
<CollectionView ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding Name}" />
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
<CollectionView.EmptyView>
<Grid>
<Label Text="Loading ..." FontSize="24" TextColor="Blue" BackgroundColor="LightBlue" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
</Grid>
</CollectionView.EmptyView>
</CollectionView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
PageWithQueryData.xaml.cs:
public partial class PageWithQueryData : ContentPage
{
public PageWithQueryData()
{
InitializeComponent();
// ... other initialization work here ...
// BUT remove `Kids.Binding(...);` line. See XAML: `ItemsSource="{Binding Items}"`.
BindingContext = new VMWithQueryData();
}
}
VMWithQueryData.cs:
class VMWithQueryData : Xamarin.Forms.BindableObject
{
public VMWithQueryData()
{
// Start an async task to query.
Xamarin.Forms.Device.BeginInvokeOnMainThread(async () => {
await QueryItemsAsync();
});
// Alternative implementation: Start a background task to query.
//QueryItemsInBackground();
}
public ObservableCollection<ItemModel> Items {
get => _items;
set {
_items = value;
OnPropertyChanged();
}
}
private ObservableCollection<ItemModel> _items;
private async Task QueryItemsAsync()
{
var names = new List<string> { "One", "Two", "Three" };
bool queryOneAtATime = false;// true;
if (queryOneAtATime) {
// Show each item as it is available.
Items = new ObservableCollection<ItemModel>();
foreach (var name in names) {
// Simulate slow query - replace with query that returns one item.
await Task.Delay(1000);
Items.Add(new ItemModel(name));
}
} else {
// Load all the items, then show them.
// Simulate slow query - replace with query that returns all data.
await Task.Delay(3000);
var items = new ObservableCollection<ItemModel>();
foreach (var name in names) {
items.Add(new ItemModel(name));
}
Items = items;
}
}
// Alternative implementation, using a background thread.
private void QueryItemsInBackground()
{
Task.Run(() => {
var names = new List<string> { "One", "Two", "Three" };
bool queryOneAtATime = false;// true;
if (queryOneAtATime) {
// Show each item as it is available.
Items = new ObservableCollection<ItemModel>();
foreach (var name in names) {
// Simulate slow query - replace with query that returns one item.
System.Threading.Thread.Sleep(1000);
Items.Add(new ItemModel(name));
}
} else {
// Load all the items, then show them.
// Simulate slow query - replace with query that returns all data.
System.Threading.Thread.Sleep(3000);
var items = new ObservableCollection<ItemModel>();
foreach (var name in names) {
items.Add(new ItemModel(name));
}
Items = items;
}
});
}
}
ItemModel.cs:
public class ItemModel
{
public ItemModel(string name)
{
Name = name;
}
public string Name { get; set; }
}
This also demonstrates <CollectionView.EmptyView> to display a message to user, while the data is being queried.
For completeness, I've included an alternative QueryItemsInBackground, that uses a background thread instead of an async method. Either approach works well.
Notice inheritance from Xamarin.Forms.BindableObject. This is one way to get an implementation of INotifyPropertyChanged. You can use any other MVVM library or technique.
Move this line of code to the end of your constructor
this.BindingContext = viewmodel;

InvalidCastException when binding a Xamarin ListView to an IEnumerable<Person>

I have this ListView in a Xamarin app:
<ListView Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{x:Static local:Person.All}" x:Name="list">
<ListView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And I'm trying to bind it to an IEnumerable<Person> by setting the ItemsSource property to the new enumerable. (Yes, I know I should create a viewmodel, but I hate MVVM with a passion!) But when there is data in the enumerable, I get this error:
System.InvalidCastException: Specified cast is not valid.
This does not happen immediately after setting ItemsSource; I have a try/catch block containing the set operation, but no exception is caught. Rather it happens as soon as I get out of the method where I'm setting the ItemsSource. There is no stack trace associated with this error; that's all I get apart from some generic "Unhandled Exception" message.
Here is the method where I am setting the ItemsSource:
private void BtnLogIn_Clicked(object sender, EventArgs e)
{
try
{
// log in
var req = WebRequest.CreateHttp($"http://{Configuration.Hostname}/api/login?systemID=1091&login={txtLogin.Text}&password={txtPassword.Text}");
var resp = (HttpWebResponse)req.GetResponse();
var cookiesData = resp.Headers.Get("Set-Cookie");
var regex = new Regex($#"{CookieManager.LoginCookieID}=(.*); expires=.*");
Login.CookieValue = regex.Match(cookiesData).Groups[1].Captures[0].Value;
list.ItemsSource = Person.All; // reload person list
}
catch (Exception ex)
{
DisplayAlert("Error", ex.ToString(), "OK");
}
}
(yes I know putting a password in a URL is a bad idea; this is just a proof of concept!)
And here is the Person class:
public class Person
{
public static IEnumerable<Person> All => GetWebData<IEnumerable<Person>>($"http://{Configuration.Hostname}/api/people", CookieManager.LoginCookieID, Login.CookieValue);
private static T GetWebData<T>(string url, string cookieKey, string cookieValue)
{
try
{
var web = WebRequest.CreateHttp(url);
web.Headers["Set-Cookie"] = $"{cookieKey}={cookieValue}";
var stream = web.GetResponse().GetResponseStream();
var sr = new StreamReader(stream);
T data;
var json = sr.ReadToEnd();
sr.Close();
try
{
data = JsonConvert.DeserializeObject<T>(json);
}
catch
{
data = JsonConvert.DeserializeObject<IEnumerable<T>>(json).Single();
}
return data;
}
catch
{
// could not access data, maybe not logged in yet?
return default(T);
}
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name => $"{FirstName} {LastName}";
}
I figured it out - looks like <Label Text="{Binding Name}" /> is not valid as a DataTemplate; I changed the Label to a TextCell and everything works!

combobox splitting values up to 1 char and only getting the first value from json

i am trying to populate my combobox with a json string with around 30 values
but it only takes the first value (4x98) and splitting it up so it is
4
x
9
8
private void bindkrydsmål()
{
{
try
{
string Url = URL_Domain + "resources/bolt-pattern";
Uri serviceUri = new Uri(Url);
using (WebClient webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8;
string api = webClient.DownloadString(serviceUri);
List<boltPatterns> values = JsonConvert.DeserializeObject<List<boltPatterns>>(api);
comboBox_Copy.DataContext = values;
}
}
catch (Exception es)
{
}
}
}
public class boltPatterns
{
public string BoltPattern { get; set; }
}
combobox xaml
<ComboBox x:Name="comboBox_Copy" ItemsSource="{Binding Path=BoltPattern}" Width="150" Height="40" Foreground="#FF00FB0B" Background="#FF303030" FontSize="16" Canvas.Left="1030" Canvas.Top="24" Style="{StaticResource ComboBoxTest2}">
api value
"[{\"BoltPattern\":\"4x98\"},{\"BoltPattern\":\"5x108\"},{\"BoltPattern\":\"5x114.3\"},{\"BoltPattern\":\"6x180\"},{\"BoltPattern\":\"4x100\"},{\"BoltPattern\":\"8x165.1\"},{\"BoltPattern\":\"5x100\"},{\"BoltPattern\":\"5x165\"},{\"BoltPattern\":\"5x120.65\"},{\"BoltPattern\":\"6x115\"},{\"BoltPattern\":\"6x127\"},{\"BoltPattern\":\"5x118\"},{\"BoltPattern\":\"5x150\"},{\"BoltPattern\":\"5x127\"},{\"BoltPattern\":null}]"
Its just need a property name to bind. Rest all is fine
DisplayMemberPath="BoltPattern"
and
comboBox_Copy.ItemsSource= values;

WPF: C# How to get selected value of Listbox?

I am trying to fetch the selected value of the listbox. When I actually try LstGroup1.SelectedItem I get the value { BoothID = "4", BoothName = "HP" } and even if i try to get the value from LstGroup1.SelectedValue the output is same. Now I want to fetch BoothID i.e. the expected output is 4 but i am unable to get so.
My ListBox name is LstGroup1.
public List<object> BoothsInGroup1 { get; set; }
// Inside the Constructor
BoothsInGroup1 = new List<object>();
//After Fetching the value add
BoothsInGroup1.Add(new { BoothID = da["BoothID"].ToString(), BoothName = da["BoothName"].ToString() });
//Now here I get
var Booth = (LstGroup1.SelectedItem);
//Output is { BoothID = "4", BoothName = "HP" }
// Expected Output 4
Suggest me how to do that.
EDIT
public partial class VotingPanel : Window
{
public List<object> BoothsInGroup1 { get; set; }
public VotingPanel()
{
InitializeComponent();
DataContext = this;
BoothsInGroup1 = new List<object>();
//Connection is done
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
FieldNameCmd.CommandText = "SELECT * FROM Booth b, BoothGroup bg where bg.GroupID=b.GroupID;";
IDataReader da = FieldNameCmd.ExecuteReader();
while (da.Read())
{
if (Group1Name.Text == da["GroupName"].ToString())
{ // Adds value to BoothsInGroup1
BoothsInGroup1.Add(new { BoothID = da["BoothID"].ToString(), BoothName = da["BoothName"].ToString() });
}
}
}
private void BtnVote_Click(object sender, RoutedEventArgs e) // on Click wanted to find the value of Selected list box
{
if (LstGroup1.SelectedIndex >= 0 && LstGroup2.SelectedIndex >= 0)
{
var Booth = (LstGroup1.SelectedItem);
//Few things to do
}
}
}
XAML
<ListBox Grid.Row="1"
Name="LstGroup1"
ItemsSource="{Binding BoothsInGroup1}"
Margin="5,1">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding BoothID}"
HorizontalAlignment="Center"
VerticalAlignment="Bottom"
FontSize="15"
FontWeight="ExtraBold"
Margin="5,3"
Grid.Column="1" />
<TextBlock Text="{Binding BoothName}"
Grid.Column="1"
VerticalAlignment="Center"
FontWeight="ExtraBold"
FontSize="30"
Margin="15" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
since you are using anonymous type to populate the listbox, so you have left with no option then an object type to cast the SelectedItem to. other approach may include Reflection to extract the field/property values.
but if you are using C# 4 or above you may leverage dynamic
if (LstGroup1.SelectedIndex >= 0 && LstGroup2.SelectedIndex >= 0)
{
//use dynamic as type to cast your anonymous object to
dynamic Booth = LstGroup1.SelectedItem as dynamic;
//Few things to do
//you may use the above variable as
string BoothID = Booth.BoothID;
string BoothName = Booth.BoothName:
}
this may solve your current issue, but I would suggest to create a class for the same for many reasons.
I think, you should try one of the following : //EDIT : This solution only works, if Booth is a class/struct
var myBooth = LstGroup1.SelectedItem as Booth;
String id =myBooth.BoothID;
String name=myBooth.BoothName:
or use a generic list with a different type :
public List<Booth> BoothsInGroup1 { get; set; }
....
var myBooth = LstGroup1.SelectedItem;
String id =myBooth.BoothID;
Stringname=myBooth.BoothName:
And if Booth isn't a class yet, add a new class:
public class Booth
{
public int BoothID { get; set; }
public String BoothName { get; set; }
}
So u can use it in your generic list, an you can fill it after databasereading
BoothsInGroup1.Add(new Booth
{
BoothID = Convert.ToInt32(da["BoothID"]),
BoothName = da["BoothName"].ToString()
});
Have you tried :
var Booth = (LstGroup1.SelectedItem);
string ID=Booth.BoothID;
string Name=Booth.BoothName:
You can always create a class called Booth to get the data in the Object Format. From My point of view Dynamic is not the right way of doing this. Once you have the Class Booth in the Solution you can run
Booth Booth1 = LstGroup1.SelectedItem as Booth;
string BoothID1 = Booth1.BoothID;
public List<object> BoothsInGroup1 { get; set; }
BoothsInGroup1 = new List<object>();
BoothsInGroup1.Add(new { BoothID = da["BoothID"].ToString(), BoothName = da["BoothName"].ToString() });
var Booth = (LstGroup1.SelectedItem);
var output = Booth.BoothID;
For those that know the type or object that they want the code will look like this:
private void lboxAccountList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//Class object = (Class)listName.SelectedItem;
// object.getName or object.getSomeVariable or object.callMethod(object.getName)
Account account = (Account)lboxAccountList.SelectedItem;
MessageBox.Show(""+account.AccountNo+" "+account.Balance);
}

Creating a Pivot in background code from Linq feed

I've currently got a class that gets and dispatches an XML feed using Linq to XML to a ListBox in my XAML page. I took this from a tutorial, and was wondering, would I be able to make it appear in a pivot?
My idea is to load the feed, and create a pivot page just in background code for each item (Something like, foreach item in my data, create a new pivot, with other content)
Is this possible?
I currently get data into a ListBox by Binding the loading and using "TextBlock Text="{Binding Id}"/>" in XAML, and loading the feed in the background code as follows:
myFeed.LoadFeed(//name of the listbox that currently has to exist in XAML)
Here is my code that loads the XML feed and dispatches to a Listbox
public class FeedItem
{
public string Id { set; get; }
public string Text { set; get; }
}
public class Feed
{
ListBox myContext;
public void LoadFeed(ListBox context)
{
myContext = context;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://myDataSource"));
request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
}
private static readonly XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request =
(HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult);
XDocument doc = XDocument.Load(response.GetResponseStream());
List<FeedItem> feedItems = (from question in doc.Descendants(m + "properties")
select new FeedItem()
{
Id = question.Descendants().ToList()[0].Value,
Text = question.Descendants().ToList()[1].Value
}).ToList();
myContext.Dispatcher.BeginInvoke(() => { myContext.ItemsSource = feedItems; });
}
}
What can be used to hold the data so it can go in a pivot?
How do i parse the response item-by-item, into a new pivot?
Yes, you can. You need to provide a datatemplate to the Pivot control. Give attention to the header template which is defined at Pivote level not on the PivotItem's one.
<Grid x:Name="LayoutRoot" Background="Transparent">
<controls:Pivot ItemsSource="{Binding MyPivots}">
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyTitle}"/>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
<controls:Pivot.ItemTemplate>
<DataTemplate>
<controls:PivotItem>
<TextBlock Text="{Binding YourRssText}" />
</controls:PivotItem>
</DataTemplate>
</controls:Pivot.ItemTemplate>
</controls:Pivot>
And the code-behind class:
public partial class MainPage : PhoneApplicationPage{
public List<RssFeed> MyPivots { get; set; }
// Constructor
public MainPage()
{
MyPivots = new List<RssFeed>
{
new RssFeed{ MyTitle = "Title1", YourRssText = "Body1"},
new RssFeed{ MyTitle = "Title2", YourRssText = "Body2"},
new RssFeed{ MyTitle = "Title3", YourRssText = "Body3"},
};
InitializeComponent();
this.DataContext = this;
}
}
public class RssFeed
{
public string MyTitle { get; set; }
public string YourRssText { get; set; }
}

Categories

Resources