【发布时间】:2015-01-24 02:55:38
【问题描述】:
我创建了一个 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) 并单击“删除”项,我的删除方法就会被激活。我的删除方法是:
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);
}
【问题讨论】:
-
btn_Delete_Click应该只删除集合中的选定项目。MenuFlyoutItem是contextMenu。当用户持有 ListViewItem 时,MenuFlyoutItem显示Delete选项,当他单击它时,它应该只删除选定的ListViewItem。我添加了DataContext as ItemProperties以获取整个 ListViewItem 对象,因此它会删除该项目。希望这是有道理的。
标签: c# listview windows-phone-8 observablecollection