I want to ensure, that the items added in my list box are ordered in ascending order according to the serial number of each item (e.g 1 item, 2 item, 4 item, 3 item should be au
In the MainPage
constructor you have the sort code, but you don't set the content to the list box, which is why it didn't display in sorted order.
var sortedList = listobj.OrderBy(item => item.AnswerName).ToList();
this.FavoriteListBox.ItemsSource = sortedList; //you were using listobj, which isn't sorted
For the FavoriteButton_Click
handler, you have a similar situation - you were sorting and saving the sorted results into a new list, which did not affect the original listobj
instance. OrderBy
is a LINQ extension which does not affect the original instance, so you can only clear and re-add the items to the original instance manually.
private void FavoriteButton_Click(object sender, RoutedEventArgs e)
{
if (listobj.Any(l => l.AnswerName == AnswerTextBlock.Text))
return;
//add
listobj.Add(new MyData { AnswerName = AnswerTextBlock.Text });
//sort (does not modify the original listobj instance!)
var sortedList = listobj.OrderBy(item => item.ToString()).ToList();
//clear and re-add all items in the sorted order
listobj.Clear();
foreach( var item in sortedList )
{
listobj.Add( item );
}
using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Create))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList));
serializer.WriteObject(fileStream, listobj);
}
}
Also as a suggestion - you don't have to use MyDataList
type, you can directly use ObservableCollection<MyData>
everywhere.
As you can see this code is getting quite hard to maintain and keep functional. For that reason I suggest you to read some book on design patterns or Windows app development, especially to learn about MVVM pattern, data-binding and INotifyPropertyChanged. These are quite essential in building maintainable and stable Windows applications.
Also I think it would be helpful to learn some better C# code conventions - for better readability with more consistent variable naming (avoiding things like Settings1
, listobj
), commenting and code structure. It takes time but the end result is well worth the effort :-) .