我创建了一个ObservableCollection并将其绑定到我的Listview。在我的项目加载到ListView之前,他们使用Linq进行排序,然后添加到ListView:
//Get's the Items and sets it
public ObservableCollection<ItemProperties> ItemCollection { get; private set; }
//Orders the Items alphabetically using the Title property
DataContext = ItemCollection.OrderBy(x => x.Title);
<!--ItemCollection has been binded to the ListView-->
<ListView ItemsSource="{Binding}"/>
我遇到的问题是我无法从收藏中删除所选项目。仅当我添加DataContext = ItemCollection.OrderBy(x => x.Title);
时才会出现此问题。如果它是DataContext = ItemCollection
,那么我可以删除所选项目。
一旦打开ContextMenu(MenuFlyout)并删除&#39;我的删除方法就会被激活。单击项目。我的删除方法是:
private void btn_Delete_Click(object sender, RoutedEventArgs e)
{
var edit_FlyOut = sender as MenuFlyoutItem;
var itemProperties = edit_FlyOut.DataContext as ItemProperties;
ItemCollection.Remove(itemProperties);
}
这是我的ItemProperties类:
public class ItemProperties : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ItemProperties() { }
private string m_Title;
public string Title
{
get { return m_Title; }
set
{
m_Title = value;
OnPropertyChanged("Title");
}
}
private string m_Post;
public string Post
{
get { return m_Post; }
set
{
m_Post = value;
OnPropertyChanged("Post");
}
}
private string m_Modified;
public string Modified
{
get { return m_Modified; }
set
{
m_Modified = value;
OnPropertyChanged("Modified");
}
}
private string m_ID;
public string ID
{
get { return m_ID; }
set
{
m_ID = value;
OnPropertyChanged("ID");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
}
修改
我如何加载我的物品:
public async void GetList()
{
var AppStorage = ApplicationData.Current.LocalFolder;
var noteFolders = await AppStorage.GetFolderAsync(@"folder\files\");
var Folders = await noteFolders.GetFoldersAsync();
ItemCollection = new ObservableCollection<ItemProperties>();
foreach (var noteFolder in Folders)
{
ItemCollection.Add(new ItemProperties { Title = readTitle, Post = readBody, ID = noteFolder.Name, Modified = timeFormat });
}
//code which readers and adds text to the properties...
DataContext = ItemCollection.OrderBy(x => x.Title);
}
答案 0 :(得分:0)
您可以从ListView中获取所选项目并将其删除:
if (lvElement.SelectedIndex == -1) return;
ItemProperties selectedProperty = (ItemProperties)lvElement.SelectedItem;
// remove selectedProperty from original collection
答案 1 :(得分:0)
我的解决方案是:
ItemCollection = new ObservableCollection<ItemProperties>(ItemCollection.OrderBy(a => a.Title));
DataContext = ItemCollection;
似乎我不得不将ItemCollection重新初始化为一个新的ObservableCollection,并一次性完成所有订单,而不是加载项目然后排序。这样做是因为它有一个列表,首先添加项目,然后是另一个必须排序的列表。为了避免这种情况,我一气呵成。上面帮助了我。我是从here得到的。