Automatically filter/order ListBox items (Windows Phone)

北城以北 提交于 2019-12-02 09:32:15

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.

Overall advice

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 :-) .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!