我的隔离存储中存有OberservableCollection。
新场景包含一个列表。 Light包含一个Xpos en Ypos属性。
如何编辑此列表?
所以我想从IsoStorage中检索它,更改2个属性然后再次保存。
希望有人可以帮助我:)。
亲切的问候, 尼尔斯
答案 0 :(得分:0)
ObservableCollection
有一个colleciton更改事件,它传递了发送它的人(基本集合)以及一系列参数。您可以收听此CollectionChanged
事件,只收听新添加的项目并对该项目执行操作。
如果您的集合是引用对象的列表,则可以直接对对象执行编辑,并且更改将在列表中进行镜像。但是,如果使用值类型列表,则需要一种标记项目的方法,以便在从列表中删除它并重新添加它时,添加不会触发无限循环。
示例:强>
class Clean<T>
{
public T Value;
public bool IsClean;
public Clean(T value, bool clean)
{
Value = value;
IsClean = clean;
}
}
此Clean类用于存储值以及标记标记(如果已处理)。
class Program
{
static void Main(string[] args)
{
ObservableCollection<Clean<int>> myCollection = new ObservableCollection<Clean<int>>();
myCollection.CollectionChanged += x_CollectionChanged;
myCollection.Add(new Clean<int>(2,false));
}
static void x_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
//Grab the collection being modified
ObservableCollection<Clean<int>> collection = sender as ObservableCollection<Clean<int>>;
if (collection == null)
{
// do some error checking action
}
//Only look at items being added
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
//New item has been added
foreach (Clean<int> newItem in e.NewItems)
{
///Only perform the operation on new "dirty" objects
if (!newItem.IsClean)
{
collection.Remove(newItem);
//Add the new modified value and mark it as clean so that
// this process isn't run again
collection.Add(new Clean<int>(newItem.Value * 2,true));
}
}
}
}
}
<强>来源:强>
ObservableCollection
MSDN Article
NotifyCollectionChangedEventHandler
MSDN Article
答案 1 :(得分:0)
我会按照正常的方式检索该集合......
public IEnumerable<Scene> GetScenes()
{
using (var filesystem = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fs = new IsolatedStorageFileStream("Scenes", FileMode.Open, filesystem))
{
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(IEnumerable<Scene>));
return serializer.ReadObject(fs) as IEnumerable<Scene>;
}
}
}
...然后编辑你需要的东西......
var myScenes = new ObservableCollection<Scene>(GetScenes());
var itemToUpdate = myScenes.Where(i => i.PropertyToCheck == "value to check");
itemToUpdate.PropertyToSet = "new value";
...并使用相同的密钥将集合保存回隔离的存储空间以识别它。
SaveScenes(myScenes);
如果您使用FileMode.Create
,它将覆盖以前的集合。
public void SaveScenes(IEnumerable<Scene> scenes)
{
using (var filesystem = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fs = new IsolatedStorageFileStream("Scenes", FileMode.Create, filesystem))
{
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(IEnumerable<Scene>));
serializer.WriteObject(fs, Scenes);
}
}
}
您可以找到similar example on MSDN。