I'm trying to use my old code in my new application. I have the following problem.
I need to call something similar to this.Loaded += OnLoaded in my new code. But I cannot because I don't have : Page in my class.
The old code:
public sealed partial class VotePage : Page
{
public VotePage()
{
this.InitializeComponent();
// This will call the OnLoaded function
this.Loaded += OnLoaded;
}
Old code (OnLoaded function):
public async void OnLoaded(object sender, RoutedEventArgs e)
{
var response = await start();
dynamic dynJson = JsonConvert.DeserializeObject(response);
foreach (var item in dynJson)
{
Object votedGame = localSettings.Values[item.slug.ToString()];
string voted = "Collapsed";
string btnVoted = "VOTE";
bool btnEnabled = true;
if(votedGame != null)
{
voted = "Visible";
btnVoted = "VOTED!";
btnEnabled = false;
}
listofGames.Add(new Games { Title = item.name, Votes = item.votes, Slug = item.slug, Voted = voted, BtnVoted = btnVoted, BtnEnabled = btnEnabled });
}
gamesList.ItemsSource = listofGames;
}
New code:
public class GamesList
{
public List<Game> Games { get; set; }
public String Name { get; set; }
public GamesList(String databaseName)
{
Name = databaseName;
// This won't work because there is no await.
Games = DataService.GetGames;
}
DataService.GetGames function:
public async Task<List<Game>> GetGames()
{
Debug.WriteLine("GET for games.");
var response = await start();
dynamic dynJson = JsonConvert.DeserializeObject(response);
foreach (var item in dynJson)
{
Object votedGame = localSettings.Values[item.slug.ToString()];
string voted = "Collapsed";
string btnVoted = "VOTE";
bool btnEnabled = true;
if (votedGame != null)
{
voted = "Visible";
btnVoted = "VOTED!";
btnEnabled = false;
}
listofGames.Add(new Game { Title = item.name, Votes = item.votes, Slug = item.slug, Voted = voted, BtnVoted = btnVoted, BtnEnabled = btnEnabled });
}
return new List<Game>();
}
Depending on where, when and how the GamesList class is initialized you could give it a static creation method as suggested in the blog post linked by #Romasz:
public sealed class GamesList
{
public List<Game> Games { get; set; }
public String Name { get; set; }
private GamesList(String databaseName)
{
Name = databaseName;
}
public static async Task<GamesList> Create(string databaseName)
{
GamesList instance = new GamesList(databaseName);
instance.Games = await DataService.GetGames();
return instance
}
...
}
You will then use the factory method to create an instance of and initialize the class asynchronously:
public VotePage()
{
this.InitializeComponent();
this.Loaded += OnLoaded;
}
public async void OnLoaded(object sender, RoutedEventArgs e)
{
DataContext = await GamesList.Create("database name...");
}
Related
I'm getting this error on DataBind(), and I don't know why since there shouldn't be anything selected.
DdState.Items.Clear();
DdState.DataSource = UsStates;
DdState.DataTextField = "Title";
DdState.DataValueField = "Title";
DdState.Items.Insert(0, String.Empty);
if (DdState.SelectedItem != null)
{
DdState.SelectedItem.Selected = false;
}
DdState.DataBind();
private IEnumerable<IStateItem> UsStates
{
get
{
var statesFolder = _sitecoreService.GetItem<ISitecoreItem>(ItemReference.BcsUs_ProductData_States.Guid);
if (statesFolder == null)
return new List<IStateItem>();
List<IStateItem> usStates = _sitecoreService.QueryChildren<IStateItem>(statesFolder).OrderBy(s => s.Title).ToList();
return usStates;
}
}
I tried putting in DdState.SelectedIndex = 0 before the DataBind(), but then I got an error that the selected index did not exist. What's going on?
If the DataSource is a list its much easier to implement. So just "convert" the UsStates IEnumerable to a List an then add it to the data source.
DdState.DataSource = UsStates.ToList();
Then choose the property of a list item as binding.
OR
public Form1()
{
InitializeComponent();
DdState.Items.Clear();
DdState.DataSource = UsStates;
DdState.DisplayMember = "Statename";
DdState.SelectedIndex = 0;
}
private List<IStateItem> UsStates
{
get
{
List<IStateItem> usStates = new List<IStateItem>();
usStates.Add(new IStateItem("California","status1"));
usStates.Add(new IStateItem("Ohio", "status3"));
return usStates;
}
}
private class IStateItem
{
public IStateItem(string statename, string stateStatus)
{
Statename = statename;
StateStatus = stateStatus;
}
public string Statename { get; set; }
public string StateStatus { get; set; }
}
Could there be something wrong with your IStateItem class?
I copy/pasted your code in a new asp.net application, made my own IStateItem class and it works.
using System;
using System.Collections.Generic;
namespace TestIt
{
public partial class Form1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FillTheList();
}
private void FillTheList()
{
ddl_TheList.Items.Clear();
ddl_TheList.DataSource = UsStates;
ddl_TheList.DataTextField = "statename";
ddl_TheList.DataValueField = "stateStatus";
//ddl_TheList.Items.Insert(0, String.Empty);
ddl_TheList.DataBind();
ddl_TheList.SelectedIndex = 0;
}
private IEnumerable<IStateItem> UsStates
{
get
{
List<IStateItem> usStates = new List<IStateItem>();
for (int i = 0; i < 10; i++)
{
usStates.Add(new IStateItem { statename = "state #" + i, stateStatus = "cool state bro" });
}
return usStates;
}
}
}
public class IStateItem
{
public string statename { get; set; }
public string stateStatus { get; set; }
}
}
I thought I had it working fine, since I had my phone unplugged and when I plugged it back in I had all the pictures working, however, when I tried to work with them, seems, it is not working as expected, since the image.Properties.Width = 0.
Can you guys help me out to have it working, please?
This is the code:
Main Page
public sealed partial class MainPage : Page
{
private GetFromJson get = new GetFromJson();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
get.GetFullResponse(GlobalVariables.apiUrl + "/" + "api/"+ GlobalVariables.shopping + "/general");
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private void btnIngresarConEmail_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(IngresarConEmail));
}
private void btnCrearCuenta_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(CrearCuenta));
}
}
Global Variables
public class GlobalVariables
{
public static string UserName;
public static string EmailAddress;
public static string Password;
public static string Name;
public static IList<Medio> Medios;
public string Stores;
public static string apiUrl = "http://ec2-52-8-2-140.us-west-1.compute.amazonaws.com";
public static string shopping = "1";
}
GetFromJson
public class GetFromJson
{
private Medio medio = new Medio();
public async void GetFullResponse(string address)
{
try
{
var client = new HttpClient();
var uri = new Uri(address);
Debug.WriteLine(uri);
var Response = await client.GetAsync(uri);
var statusCode = Response.StatusCode;
Response.EnsureSuccessStatusCode();
var ResponseText = await Response.Content.ReadAsStringAsync();
string myJson = ResponseText;
Debug.WriteLine(myJson);
medio.deserializeAndConvert(myJson);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
Medio
public class Medio
{
public string id { get; set; }
public string name { get; set; }
public string type { get; set; }
public string img { get; set; }
public string medios_id { get; set; }
public void deserializeAndConvert(string aaa)
{
JObject myGeneral = JObject.Parse(aaa);
IList<JToken> results = myGeneral["resp"]["medios"].Children().ToList();
IList<Medio> searchResults = new List<Medio>();
foreach (JToken result in results)
{
Medio searchResult = JsonConvert.DeserializeObject<Medio>(result.ToString());
searchResults.Add(searchResult);
Debug.WriteLine(searchResults);
}
Debug.WriteLine(searchResults.Count);
GlobalVariables.Medios = searchResults;
var selected = GlobalVariables.Medios.Where(item => item.img!=null);
Debug.WriteLine(GlobalVariables.Medios[0].ToString());
}
}
And the one that saves the pics into the disk (the Windows Phone internal memory)
public sealed partial class CrearCuenta : Page
{
public CrearCuenta()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
QueryPicturesToShow();
}
public async void QueryPicturesToShow()
{
var pics = from medio in GlobalVariables.Medios
where medio.img != null
select new { Name = medio.name, Id = medio.id, Picture = medio.img };
foreach (var item in pics)
{
Debug.WriteLine(item.Name);
Debug.WriteLine(item.Id);
Debug.WriteLine(item.Picture);
await savePicToDisk(item.Picture, item.Name, item.Id);
}
}
private async Task savePicToDisk(string picAddress, string picName, string picId)
{
StorageFolder folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("carpetaFunciona", CreationCollisionOption.OpenIfExists);
StorageFile file = await folder.CreateFileAsync((picName + picId + ".png"), CreationCollisionOption.ReplaceExisting);
string url = GlobalVariables.apiUrl + picAddress;
Debug.WriteLine(url);
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
byte[] responseBytes = await client.GetByteArrayAsync(url);
var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
using (var outputStream = stream.GetOutputStreamAt(0))
{
DataWriter writer = new DataWriter(outputStream);
writer.WriteBytes(responseBytes);
await writer.StoreAsync();
await outputStream.FlushAsync();
}
Debug.WriteLine(file.Name);
}
Thanks a lot!!!
I think your problem is your service, all images are null:
I want to delete the row by its Id but I cant delete it by its Id.like for example the values are
date|time|Floor|zone|Latitude|longitude and I want to delete a row of its while selecting it but i cannot.below is the class where i wrote all main functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
public void AddInfo()
{
//string f = Checkin.Floor_st;
Debug.WriteLine(Checkin.a);
string z = Checkin.Zone_st;
DbHelper Db_helper = new DbHelper();
Db_helper.Insert((new historyTableSQlite
{
Date = DateTime.Now.ToShortDateString(),
Time = DateTime.Now.ToShortTimeString(),
Zone = "D",
Floor = "7",
latitude =12344.66,
longtitude = -122.56
}));
}
// Delete specific contact
public void DeleteContact(int Id)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
var existingvalue = dbConn.Query<historyTableSQlite>("select * from historyTableSQlite where Id =" + Id).FirstOrDefault();
if (existingvalue != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingvalue);
});
}
}
}
//Delete all contactlist or delete Contacts table
public void DeleteAllContact()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
//dbConn.RunInTransaction(() =>
// {
dbConn.DropTable<historyTableSQlite>();
dbConn.CreateTable<historyTableSQlite>();
dbConn.Dispose();
dbConn.Close();
//});
}
}
}
below is the class where I show the values
public partial class History : PhoneApplicationPage
{
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
DbHelper Db_helper = new DbHelper();
//int Selected_HistoryId;
public static int Selected_HistoryId { get; set; }
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
public History()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Db_helper.AddInfo();
ReadHistoryList_Loaded();
// Selected_HistoryId = int.Parse(NavigationContext.QueryString["SelectedHistoryID"]);
}
public void ReadHistoryList_Loaded()
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
//Latest contact ID can Display first
}
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
int Selected_HistoryId = listitem.Id;
}
}
public void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(Selected_HistoryId);
}
private void DeleteAll_Click(object sender, EventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.DeleteAllContact();//delete all db
DB_HistoryList.Clear();
ListData.ItemsSource = DB_HistoryList;
}
//public void updateDB(string fl,string zo,double la, double lo)
//{
// using (var db = new SQLiteConnection(dbPath))
// {
// var existing = db.Query<historyTableSQlite>("select * from historyTableSQlite").FirstOrDefault();
// if (existing != null)
// {
// existing.Floor = fl;
// existing.Zone = zo;
// existing.latitude = la;
// existing.longtitude = lo;
// db.RunInTransaction(() =>
// {
// db.Update(existing);
// });
// }
// }
//}
//public void AddDb(string fl, string zo, double la, double lo)
//{
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
// using (var db = new SQLiteConnection(dbPath))
// {
// db.RunInTransaction(() =>
// {
// db.Insert(new historyTableSQlite()
// {
// Date = DateTime.Today.ToShortDateString(),
// Time = DateTime.Now.ToShortTimeString(),
// Floor = fl,
// Zone = zo,
// longtitude = la,
// latitude = lo
// });
// Debug.WriteLine(db);
// });
// }
}
I am updating the table class so that it is easy to understand
public class historyTableSQlite : INotifyPropertyChanged
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id { get; set; }
private int idvalue;
private string dateValue = string.Empty;
public string Date {
get { return this.dateValue; }
set
{
if (value != this.dateValue)
{
this.dateValue = value;
NotifyPropertyChanged("Date");
}
}
}
private string timeValue = string.Empty;
public string Time
{
get { return this.timeValue; }
set
{
if (value != this.timeValue)
{
this.timeValue = value;
NotifyPropertyChanged("Time");
}
}
}
private string floorValue = string.Empty;
public string Floor
{
get { return this.floorValue; }
set
{
if (value != this.floorValue)
{
this.floorValue = value;
NotifyPropertyChanged("Floor");
}
}
}
public string zoneValue;
public string Zone
{
get { return this.zoneValue; }
set
{
if (value != this.zoneValue)
{
this.zoneValue = value;
NotifyPropertyChanged("Zone");
}
}
}
private double latValue;
public double latitude
{
get { return latValue; }
set
{
if (value != this.latValue)
{
this.latValue = value;
NotifyPropertyChanged("Latitude");
}
}
}
private double lonValue;
public double longtitude
{
get { return this.lonValue; }
set
{
if (value != this.lonValue)
{
this.lonValue = value;
NotifyPropertyChanged("Longitude");
}
}
}
// public string isMarkPoint { get; set; }
public historyTableSQlite()
{
}
public historyTableSQlite(string date,string time,string floor,string zone,double lat,double lng)
{
Date = date;
Time = time;
Floor = floor;
Zone = zone;
latitude = lat;
longtitude = lng;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
when i click the delete i.e the method delete_click i cant delete the row
EDIT: I cut and pasted your code incorrectly...you have very poor alignment :)
Okay I think I finally got your code to run, your problem is here
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
// this will get destroy when the function exits, it's local decalartion
int Selected_HistoryId = listitem.Id;
// History.Selected_HistoryId = listitem.Id;
// you need to set the Property not a local variable
}
}
you made a local variable named the same as the Property it should be
History.Selected_HistoryId = listitem.Id;
public void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(History.Selected_HistoryId);
}
I am developing an windows phone app using sqlite database.I am able to show out the database and delete the particular row I want to delete.But the problem is after I select the row and click delete the row does not vanishes at that time.I have to renter that page to see that it is deleted.
Below here is the code of the class where I use the click_delete event
public partial class History : PhoneApplicationPage
{
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
DbHelper Db_helper = new DbHelper();
//public static int Selected_HistoryId;
//int Selected_HistoryId;
public static int Selected_HistoryId {get; set;}
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
public History()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Db_helper.AddInfo();
ReadHistoryList_Loaded();
// Selected_HistoryId = int.Parse(NavigationContext.QueryString["SelectedHistoryID"]);
}
public void ReadHistoryList_Loaded()
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
//Latest contact ID can Display first
}
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
History.Selected_HistoryId = listitem.Id;
}
}
private void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(History.Selected_HistoryId);
NavigationService.Navigate(new Uri("/History.xaml", UriKind.Relative));
}
private void DeleteAll_Click(object sender, EventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.DeleteAllContact();//delete all DB contacts
DB_HistoryList.Clear();//Clear collections
ListData.ItemsSource = DB_HistoryList;
}
}
}
below is the class with all main functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
public void AddInfo()
{
DbHelper Db_helper = new DbHelper();
Db_helper.Insert((new historyTableSQlite
{
Date = DateTime.Now.ToShortDateString(),
Time = DateTime.Now.ToShortTimeString(),
Zone = Checkin.Zone_st,
Floor = Checkin.Floor_st,
latitude = Checkin.Latitud_do,
longtitude = Checkin.Longtitude_do
}));
}
// Delete specific contact
public void DeleteContact(int Id)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
var existingvalue = dbConn.Query<historyTableSQlite>("select * from historyTableSQlite where Id =" + Id).FirstOrDefault();
if (existingvalue != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingvalue);
});
}
}
}
//Delete all contactlist or delete Contacts table
public void DeleteAllContact()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
//dbConn.RunInTransaction(() =>
// {
dbConn.DropTable<historyTableSQlite>();
dbConn.CreateTable<historyTableSQlite>();
dbConn.Dispose();
dbConn.Close();
//});
}
}
below is the class with all tables
public class historyTableSQlite : INotifyPropertyChanged
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id
{
get;
set;
}
private int idValue;
private string dateValue = string.Empty;
public string Date
{
get { return this.dateValue; }
set
{
if (value != this.dateValue)
{
this.dateValue = value;
NotifyPropertyChanged("Date");
}
}
}
private string timeValue = string.Empty;
public string Time
{
get { return this.timeValue; }
set
{
if (value != this.timeValue)
{
this.timeValue = value;
NotifyPropertyChanged("Time");
}
}
}
private string floorValue = string.Empty;
public string Floor
{
get { return this.floorValue; }
set
{
if (value != this.floorValue)
{
this.floorValue = value;
NotifyPropertyChanged("Floor");
}
}
}
public string zoneValue;
public string Zone
{
get { return this.zoneValue; }
set
{
if (value != this.zoneValue)
{
this.zoneValue = value;
NotifyPropertyChanged("Zone");
}
}
}
private double latValue;
public double latitude
{
get { return latValue; }
set
{
if (value != this.latValue)
{
this.latValue = value;
NotifyPropertyChanged("Latitude");
}
}
}
private double lonValue;
public double longtitude
{
get { return this.lonValue; }
set
{
if (value != this.lonValue)
{
this.lonValue = value;
NotifyPropertyChanged("Longitude");
}
}
}
// public string isMarkPoint { get; set; }
public historyTableSQlite()
{
}
public historyTableSQlite(string date, string time, string floor, string zone, double lat, double lng)
{
Date = date;
Time = time;
Floor = floor;
Zone = zone;
latitude = lat;
longtitude = lng;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
If you delete the item from your ObservableCollection, it will notify the ListBox to update its container.
In your code you have
// this is correct
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
But your problem is that you don't actually link your ListBox to it.
In your code you create a copy (and the worst kind of copy given what you're trying to do) and you set the ListBox ItemsSource to it. See below (you have this)
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
So basically, your ListBox is not an ObservableCollection but it's a List structure.
Deleting and Inserting into the List will not update the ListBox's UI.
Get rid of this List, find another way to sort your ObservableCollection.
Then you can basically do this
ListData.ItemsSource = DB_HistoryList; // set the listbox to the actual obs collection
DB_HistoryList.RemoveAt(i); // remove the item at index i
DB_HistoryList.RemoveItem(object); // remove the object that matches
I'm stuck with following XML problem.
This is my XML file:
<POIs lastUsedId="9000010">
<POI id="9000010" name="München"><Latitude>48.139126</Latitude><Longitude>11.5801863</Longitude>
<Address>muenchen</Address><PhotoDescription>Hofbräuhaus</PhotoDescription>
<Photos directory="_x002F_pics"><PhotoFile>pic4poi_9000010-01.jpg</PhotoFile>
<PhotoFile>pic4poi_9000010-02.jpg</PhotoFile><PhotoFile>pic4poi_9000010-03.jpg</PhotoFile>
<PhotoFile>pic4poi_9000010-04.jpg</PhotoFile></Photos>
<InformationFile>infos\info4poi_9000010.txt</InformationFile></POI>
</POIs>
And here is my code to read the file:
XDocument doc = XDocument.Load(s);
lastID = Int32.Parse(doc.Root.Attribute("lastUsedId").Value.ToString());
CultureInfo cultureInfo = new CultureInfo("en-GB");
var pois = from res in doc.Descendants("POI")
select new
{
id = Int32.Parse(res.Attribute("id").Value.ToString()),
name = res.Attribute("name").Value.ToString(),
latitude = Double.Parse(res.Element("Latitude").Value, cultureInfo),
longitude = Double.Parse(res.Element("Longitude").Value, cultureInfo),
address = res.Element("Address").Value.ToString(),
photoDesc = res.Element("PhotoDescription").Value.ToString(),
photoDir = XmlConvert.DecodeName(res.Element("Photos").Attribute("directory").Value.ToString()),
photoFiles = from a in doc.Descendants("Photos")
select new
{
photo = a.Element("PhotoFile").Value.ToString()
},
info = res.Element("InformationFile").Value.ToString()
};
foreach (var poi in pois)
{
IEnumerable<string> pF = (poi.photoFiles as IEnumerable<string>);
List<string> photoFiles = null;
if(pF != null)
photoFiles = pF.ToList<string>();
AddPushpin(poi.id, poi.name, poi.latitude, poi.longitude, poi.address, poi.photoDesc, poi.photoDir, photoFiles, poi.info);
};
I'm unsure about the part with the PhotoFiles because I get an unknown Object error when I try to read the Pushpin.
This what my Pushpin looks like:
public class MyPushpin : Pushpin
{
public int ID { get; set; }
public string Address { get; set; }
public string PhotoDesc { get; set; }
public string PhotoDir { get; set; }
public List<string> PhotoFiles { get; set; }
public MyPushpin() { }
public MyPushpin(int id, string name, double latitude, double longitude, string address, string photoDesc, string photoDir, List<string> photoFiles, string info)
{
Location loc = new Location(latitude, longitude);
this.ID = id;
this.Location = loc;
this.Name = name;
this.Address = address;
this.PhotoDesc = photoDesc;
this.PhotoDir = photoDir;
this.PhotoFiles = photoFiles;
this.Tag = info;
}
public void Update(string name , string photoDesc, List<string> photoFiles, string info)
{
this.Name = name;
this.PhotoDesc = photoDesc;
this.PhotoFiles = photoFiles;
this.Tag = info;
}
public override string ToString()
{
return String.Format("{0} - {1}", this.ID, this.Location, this.Address, this.PhotoDesc, this.PhotoDir, this.Tag);
}
And that's the code how I would like to use the file info in the custom Pushpin:
public partial class Gallery : ChildWindow
{
List<string> pics = null;
public Gallery(MyPushpin currentPin)
{
InitializeComponent();
pics = currentPin.PhotoFiles;
Loaded += (a, b) => {
LoadImages();
};
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
Close();
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
Close();
}
private void LoadImages()
{
List<Picture> coll = new List<Picture>();
pics.ForEach(delegate(String url)
{
coll.Add(AddPicture("url"));
});
//coll.Add(AddPicture("/pics/pic4poi_9000010-01.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-02.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-03.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-04.jpg"));
Preview.Source = new BitmapImage(
new Uri(
"/pics/pic4poi_9000010-01.jpg",
UriKind.Relative));
lbImage.ItemsSource = coll;
}
private Picture AddPicture(string path)
{
return new Picture
{
Href = new BitmapImage(
new Uri(
path,
UriKind.Relative))
};
}
private void lbImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Preview.Source = ((Picture)lbImage.SelectedItem).Href;
}
}
public class Picture
{
public ImageSource Href { get; set; }
THX for your time
Chau
Could you please describe the problem that you are having in more detail. Have you debugged into it, where does it fail, what is the exception? What do you expect it to do.
Off the top of my head, this code looks wrong:
photoFiles = from a in doc.Descendants("Photos")
select new
{
photo = a.Element("PhotoFile").Value.ToString()
},
Replace doc with res, because you want the child elements of the current element, not of the document. Also you can use Elements here instead of Descendants since they are direct children. Also since there are multiple photo files, try a SelectMany (from a ... from b ...):
photoFiles = from a in res.Elements("Photos")
from b in a.Elements("PhotoFile")
select new
{
photo = b.Value.ToString()
},