I created a Windows phone 8.1 application with a listview on Startpage.xaml. When I update listview values, I don't see the changes on the phone until I close and open the application again. I tried to update the listview when I clicked the refresh button, but unsuccessfully. Anyone know how to update a listview when I click the refresh button?
How I fill in data in the listview:
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
this.navigationHelper.OnNavigatedTo(e);
HttpClient http = new HttpClient();
string str = ((ComboBoxItem)cbox.SelectedItem).Content.ToString();
var response = await http.GetStringAsync("http://mywebpage.si/events/apis/facebook_events.php?city=" + str + "&user=" + uporabnik.user);
var FSfeed = JsonConvert.DeserializeObject<List<Class1>>(response);
Reviews.ItemsSource = FSfeed;
}
My class:
public class Class1
{
public string title { get; set; }
public string description { get; set; }
public string image { get; set; }
public string start { get; set; }
public string end { get; set; }
public string location { get; set; }
public string city { get; set; }
public int id { get; set; }
}
Refresh button:
private async void refresh_Click(object sender, RoutedEventArgs e)
{
HttpClient http = new HttpClient();
string str = ((ComboBoxItem)cbox.SelectedItem).Content.ToString();
var response = await http.GetStringAsync("http://mywebpage.si/events/apis/facebook_events.php?city=" + str + "&user=" + uporabnik.user);
var FSfeed = JsonConvert.DeserializeObject<List<Class1>>(response);
Reviews.ItemsSource = FSfeed;
}
I also tried to refresh like this, but unsuccessfully:
private async void refresh_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(PivotPage));
}
To update the view you need to update the binding to ItemSource:
List<Class1> mySource = new List<Class1>();
Binding binding = new Binding { Source = mySource };
BindingOperations.SetBinding(myListView, Windows.UI.Xaml.Controls.ListView.ItemsSourceProperty, binding);
Related
I created a custom picker with the help of Lucas Zhang which you can check in the link
xamarin custom multiple picker
Now I have another question with this problem. When user select a group or groups, I need access to these selected parameters.
public class Grup
{
public int ID { get; set; }
public string GroupName { get; set; }
public Nullable<int> SubsID { get; set; }
}
This is the model I use. Picker reads Groupnames through ViewModel which is shown below.
public class NewUserViewModel
{
public List<Grup> GroupList { get; set; }
public List<Grup> SelectedGroup { get; set; }
}
And I want save these parameters which came from every pickers in the view to here and furthermore I will send them to database through API.Question is how can I access these IDs when user select them and click save button.
An easy way to do this is to listen for picker's selection events and then get the result of each selection by iterating over the pickerStack
like this(base on Lucas Zhang's sample):
in PickerView :
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PickerView : ContentView
{
public Group SelectGroup; // add the SelectGroup property which save the result after you select
public ObservableCollection<Group> pickerSource { get; set; }
public PickerView(ObservableCollection<Group> source) //here i change the source to your Group model
{
InitializeComponent();
picker.ItemsSource = source;
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var stack = this.Parent as StackLayout;
stack.Children.Remove(this);
}
private void picker_SelectedIndexChanged(object sender, EventArgs e)
{
var picker = sender as Picker;
SelectGroup = (Group)picker.SelectedItem;
}
}
in PickerView.xaml just add the SelectedIndexChanged event:
<Picker Grid.Column="0" x:Name="picker" Title="{Binding GroupName}" ItemDisplayBinding="{Binding ID}" TitleColor="Red" SelectedIndexChanged="picker_SelectedIndexChanged" />
in your page :
public partial class MutiPicker : ContentPage
{
public MutiPicker()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
var source = new ObservableCollection<Group>() { new Group() { ID=111,GroupName="AAA",SubsID=1}, new Group() { ID = 222, GroupName = "BBB", SubsID = 2 }, new Group() { ID = 333, GroupName = "CCC", SubsID = 3 } };
pickerStack.Children.Add(new PickerView(source));
}
//iterate over your pickerviews
private void Update_Clicker(object sender, EventArgs e)
{
foreach (var pickerview in pickerStack.Children)
{
if (pickerview is PickerView && ((PickerView)pickerview).SelectGroup != null)
{
var selectgroup = ((PickerView)pickerview).SelectGroup;//here you will get your select group,then you could get its ID ,GroupName or SubsID
}
}
}
}
I need some help with passing the ListView Tapped Id (which I get from a json).
I populate the listView with an API call to a server:
private async void searchButton_Click(object sender, RoutedEventArgs e)
{
var textFrom = odTextBox.Text;
var textTo = doTextBox.Text;
var searchResult = await PrevoziApi.SearchRidesAsync(textFrom, textTo, datePicker.Date.UtcDateTime);
var array = searchResult.CarshareList
.OrderBy(cs => cs.Time)
.Select(cs => cs.Contact + " " + cs.Time)
.ToArray();
listView.ItemsSource = array;
}
Now, when I click on an item of listView, I want to navigate to another page(CarShareDetailedPage) and make another call to the API, to get more detailed data about that item. So I need to pass the selectedItem id from one page to other. How do I do that ?
I'm navigating to another page like this:
private void listView_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(CarShareDetailedPage), listView.SelectedIndex);
}
The OnNagiatedMethod on that page is:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var value = e.ToString();
carShareTextBox.Text = value;
}
And my json class is:
public class CarshareList
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("from_id")]
public string FromId { get; set; }
[JsonProperty("from_country")]
public string FromCountry { get; set; }
[JsonProperty("from_country_name")]
public string FromCountryName { get; set; }
[JsonProperty("to_id")]
public string ToId { get; set; }
[JsonProperty("to")]
public string To { get; set; }
[JsonProperty("to_country")]
public string ToCountry { get; set; }
[JsonProperty("to_country_name")]
public string ToCountryName { get; set; }
[JsonProperty("time")]
public string Time { get; set; }
[JsonProperty("date_iso8601")]
public DateTime DateIso8601 { get; set; }
[JsonProperty("added")]
public DateTime Added { get; set; }
[JsonProperty("price")]
public double? Price { get; set; }
[JsonProperty("num_people")]
public double NumPeople { get; set; }
[JsonProperty("author")]
public string Author { get; set; }
[JsonProperty("is_author")]
public string IsAuthor { get; set; }
[JsonProperty("comment")]
public string Comment { get; set; }
[JsonProperty("contact")]
public string Contact { get; set; }
[JsonProperty("date")]
public string Date { get; set; }
[JsonProperty("full")]
public string Full { get; set; }
[JsonProperty("insured")]
public string Insured { get; set; }
[JsonProperty("share_type")]
public string ShareType { get; set; }
[JsonProperty("confirmed_contact")]
public string ConfirmedContact { get; set; }
[JsonProperty("bookmark")]
public object Bookmark { get; set; }
[JsonProperty("from")]
public string From { get; set; }
}
public class CarshareResponse
{
[JsonProperty("search_type")]
public string SearchType { get; set; }
[JsonProperty("carshare_list")]
public IList<CarshareList> CarshareList { get; set; }
}
Let me say this is the first time ever I'm doing any work with Apis and json.
Thanks for your help!
EDIT: I added the code for the API below, so this now should be all the code I have.
public class PrevoziApi
{ public static async Task<CarshareResponse> SearchRidesAsync(
string fromCity,
string toCity,
DateTime date,
string type = "shares",
CancellationToken token = default(CancellationToken))
{
using (var client = new RestClient("https://prevoz.org/api/"))
{
var request = new RestRequest("search/" + type + "/", HttpMethod.Get);
request.AddQueryParameter("f", fromCity);
request.AddQueryParameter("fc", "SI");
request.AddQueryParameter("t", toCity);
request.AddQueryParameter("tc", "SI");
request.AddQueryParameter("d", date.ToString("yyyy-MM-dd"));
request.AddQueryParameter("exact", "true");
return
(await client.Execute<CarshareResponse>(request, token)).Data;
}
}
}
So with this, you are ordering by the time but displaying a string only that says "[Contact] [Time]". This in-and-of-itself does not hold any relation to the JSON that was returned from your search method. What you'll want to do is instead of making it an array, instead making a List<> object that can store some additional "background" data about that request to send off.
This will require a bit more effort though on your end. You will want to create a class
public class CarItemView {
public string DisplayText {get; set;}
public int ID {get; set;}
}
and fill it with whatever data you want to pass along. Then in your filtering you would do:
List<CarItemView> array = searchResult.CarshareList
.OrderBy(cs => cs.Time)
.Select(cs => new { DisplayText = cs.Contact + " " + cs.Time, ID = cs.Id}).ToList();
You will then, in your XAML, have to add a template to your listview for display. (Note, this is a real rough outline for a XAML Template)
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding DisplayText}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
NOW when you get your selected item changed event fired, you can handle it and get the ID.
private void listView_Tapped(object sender, TappedRoutedEventArgs e)
{
var obj = (CarItemView) listView.SelectedItem; // convert item to our new class
Frame.Navigate(typeof(CarShareDetailedPage), obj.Id.ToString()); // send ID as string
}
Then for the receiving page:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var value = e.ToString();
carShareTextBox.Text = value; // will show the ID number
var caritemret = /* write a new restful function to return based on ID */
}
UPDATE: This answer was updated from original to reflect the use of an array instead of a list<> object
I hope this helps!
This works:
private async void searchButton_Click(object sender, RoutedEventArgs e)
{
var textFrom = odTextBox.Text;
var textTo = doTextBox.Text;
var searchResult = await PrevoziApi.SearchRidesAsync(textFrom, textTo, datePicker.Date.UtcDateTime);
List<CarItemView> array = searchResult.CarshareList
.OrderBy(cs => cs.Time)
.Select(cs => new CarItemView { DisplayText = cs.Contact + " " + cs.Time, Id = cs.Id })
.ToList();
listView.ItemsSource = array;
}
private void listView_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
var obj = (CarItemView)listView.SelectedItem; // convert item to our new class
Frame.Navigate(typeof(CarShareDetailedPage), obj.Id); // send ID as string
}
And on navigated to method on the destination page:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var value = e.Parameter.ToString();
carShareTextBox.Text = value; // will show the ID number
/* write a new restful function to return based on ID */
}
Thanks #daniel, it was mostly as you suggested, with a few errors, but with the help of some guys at the c# chat channel I managed. Thanks to all.
This is my code:
But I will Add the values (see code) if someone clicked the Button "Einfügen".
But it doesn't work, It only change his values!
Thanks for all helpers!
private void Einfügen_Click(object sender, RoutedEventArgs e)
{
var itemsEnd = new List<Plan>();
itemsEnd.Add(new Plan(LinieZ, Convert.ToString(Kurs.SelectedItem), AbfZ, VonZ, NachZ, AnkZ, "---"));
Plan.ItemsSource = itemsEnd;
}
class Plan
{
public string Linie { get; set; }
public string Kurs { get; set; }
public string Abfahrt { get; set; }
public string Von { get; set; }
public string Nach { get; set; }
public string Ankunft { get; set; }
public string Pause { get; set; }
public Plan(string Linie, string Kurs, string Abfahrt, string Von, string Nach, string Ankunft, string Pause)
{
this.Linie = Linie;
this.Kurs = Kurs;
this.Abfahrt = Abfahrt;
this.Von = Von;
this.Nach = Nach;
this.Ankunft = Ankunft;
this.Pause = Pause;
}
}
The problem is that you are resetting the ItemsSource each time to a brand new List (of size 1). You are not appending to the List, but instead, you are creating a List that only has the new item, then setting that List to the DataGrid.
You can have a predefined list that you add to.
Something like:
private ObservableCollection<Plan> _items = new ObservableCollection<Plan>();
public Window()
{
InitializeComponent();
Plan.ItemsSource = _items;
}
private void Einfügen_Click(object sender, RoutedEventArgs e)
{
_items.Add(new Plan(LinieZ, Convert.ToString(Kurs.SelectedItem), AbfZ, VonZ, NachZ, AnkZ, "---"));
}
Though, I would suggest not going this route. Look into MVVM, DataBinding, and Commands. Ideally, you would want to create a ViewModel that contains an ObservableCollection that is bound to the DataGrid. Inside that ViewModel will be a command that will add items to that ObservableCollection.
I am a Final Year Computer Science student trying to develop a Windows 8 phone app and I am very new to this type of development.
I am using a Windows Azure account with a mobile service and a database connection to connect to Visual Studio 2012.
I am trying to allow users to create an account to use my app, however when they enter any details they are not being saved to the table in the database. I am getting the following debugging error when I run my code and press the register button:
"Application_UnhandledException"
Below is what my code looks like.
This is from the CreateAccount.xaml.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
namespace IME.Miscellaneous
{
public class accountDetails
{
// Setting up the items for inclusion in the createAccount table
public string Id { get; set; }
[JsonProperty(PropertyName = "userpassword")]
public string Password { get; set; }
[JsonProperty(PropertyName = "securityQuestion1")]
public string SecurityQuestion1 { get; set; }
[JsonProperty(PropertyName = "securityQuestion2")]
public string SecurityQuestion2 { get; set; }
[JsonProperty(PropertyName = "securityQuestion3")]
public string SecurityQuestion3 { get; set; }
[JsonProperty(PropertyName = "answer1")]
public string SecurityAnswer1 { get; set; }
[JsonProperty(PropertyName = "answer2")]
public string SecurityAnswer2 { get; set; }
[JsonProperty(PropertyName = "answer3")]
public string SecurityAnswer3 { get; set; }
}
public partial class CreateAccount : PhoneApplicationPage
{
private MobileServiceCollection<accountDetails, accountDetails> items;
private IMobileServiceTable<accountDetails> accountTable = App.MobileService.GetTable<accountDetails>();
public CreateAccount()
{
InitializeComponent();
}
private async void InsertAccountInfo(accountDetails accountDetailsItem)
{
// This code inserts a new item into the database. When the operation completes
// and Mobile Services has assigned an Id, the item is added
await accountTable.InsertAsync(accountDetailsItem);
items.Add(accountDetailsItem);
}
private async void RefreshAccountInfo()
{
// This code refreshes the entries in the list view be querying the createAccount table.
try
{
items = await accountTable
.Where(accountDetailsItem => accountDetailsItem.Password == "")
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
}
}
private void Register_Button_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
// Brings the user to the Home hub page
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
// When button is clicked the accountDetails table is updated with the password
//var user = new accountDetails { Id = ID_textbox.Text, Password = Password_Text.Password, SecurityQuestion1 = Security_Question_1.Text, SecurityQuestion2 = Security_Question_2.Text,
// SecurityQuestion3 = Security_Question_3.Text, SecurityAnswer1 = Security_Question_1_Answer.Text, SecurityAnswer2 = Security_Question_2_Answer.Text,
// SecurityAnswer3 = Security_Question_3_Answer.Text};
// InsertAccountInfo(user);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
RefreshAccountInfo();
}
private void Security_Question_1_Answer_GotFocus(object sender, RoutedEventArgs e)
{
// Sets the textbox to empty when the user clicks on it
TextBox securityAnswerOne = (TextBox)sender;
securityAnswerOne.Text = string.Empty;
securityAnswerOne.GotFocus -= Security_Question_1_Answer_GotFocus;
}
private void Security_Question_2_Answer_GotFocus(object sender, RoutedEventArgs e)
{
// Sets the textbox to empty when the user clicks on it
TextBox securityAnswerTwo = (TextBox)sender;
securityAnswerTwo.Text = string.Empty;
securityAnswerTwo.GotFocus -= Security_Question_2_Answer_GotFocus;
}
private void Security_Question_3_Answer_GotFocus(object sender, RoutedEventArgs e)
{
// Sets the textbox to empty when the user clicks on it
TextBox securityAnswerThree = (TextBox)sender;
securityAnswerThree.Text = string.Empty;
securityAnswerThree.GotFocus -= Security_Question_3_Answer_GotFocus;
}
private void Security_Question_3_Answer_LostFocus(object sender, RoutedEventArgs e)
{
TextBox securityAnswerThree = (TextBox)sender;
if (String.IsNullOrEmpty(Security_Question_3_Answer.Text))
{
securityAnswerThree.Text = "Please Enter an answer";
securityAnswerThree.LostFocus -= Security_Question_3_Answer_LostFocus;
}
}
private void Security_Question_2_Answer_LostFocus(object sender, RoutedEventArgs e)
{
TextBox securityAnswerTwo = (TextBox)sender;
if (String.IsNullOrEmpty(Security_Question_2_Answer.Text))
{
securityAnswerTwo.Text = "Please Enter an answer";
securityAnswerTwo.LostFocus -= Security_Question_2_Answer_LostFocus;
}
}
private void Security_Question_1_Answer_LostFocus(object sender, RoutedEventArgs e)
{
TextBox securityAnswerOne = (TextBox)sender;
if (String.IsNullOrEmpty(Security_Question_3_Answer.Text))
{
securityAnswerOne.Text = "Please Enter an answer";
securityAnswerOne.LostFocus -= Security_Question_3_Answer_LostFocus;
}
}
}
}
This is from the App.xaml.cs file:
// Creating account details table
public class accountDetails
{
public int id { get; set; }
public string userpassword { get; set; }
public string securityQuestion1 { get; set; }
public string securityQuestion2 { get; set; }
public string securityQuestion3 { get; set; }
public string answer1 { get; set; }
public string answer2 { get; set; }
public string answer3 { get; set; }
public accountDetails(string p, string sq1, string sq2, string sq3, string a1, string a2, string a3)
{
// Creating the constructor
userpassword = p;
securityQuestion1 = sq1;
securityQuestion2 = sq2;
securityQuestion3 = sq3;
answer1 = a1;
answer2 = a2;
answer3 = a3;
}
}
The table in the database is called "CreateAccount" also.
Any help would be greatly appreciated.
For some reason, the Page_PreRenderComplete() is not firing for me in a user web control. Here is my code behind, any ideas why?
public partial class Views_CMSWebParts_GSAMetaTags : System.Web.UI.UserControl
{
public string Content { get; set; }
public string LastModifiedDate { get; set; }
public string PageTitle { get; set; }
public string PageDescription { get; set; }
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
if (CMSContext.CurrentDocument.NodeClassName.Equals("ctv.DailyContent")
|| CMSContext.CurrentDocument.NodeClassName.Equals("ctv.Segment")
|| CMSContext.CurrentDocument.NodeClassName.Equals("ctv.segmentContainer"))
{
Content = "news-and-articles";
//Published Date
LastModifiedDate = ValidationHelper.GetString(CMSContext.CurrentDocument.GetValue("DocumentModifiedWhen"), "");
PageTitle = CMSContext.CurrentPageInfo.DocumentPageTitle;
PageDescription = CMSContext.CurrentPageInfo.DocumentPageDescription;
}else if (CMSContext.CurrentDocument.DocumentName.Equals("Video"))
{
//using document name in this case becuase Video page type is Page (menu item)
Content = "video";
}
}
}
I don't think a UserControl has a PreRenderComplete event. A Page does, but not a UserControl. A UserControl does have a PreRender event, as well as a Render event. You can use it like this:
protected void Page_Load(object sender, EventArgs e)
{
this.PreRender += new EventHandler([method name]);
}