首页 > 解决方案 > 将列表视图中的选定项目添加到另一个列表视图

问题描述

我想将每个已处理SelectedItem的 from添加ListView AListView B一种历史记录。如果我只为一个对象编写此代码,但当我尝试向其中添加另一个对象时,ListView B它没有显示任何内容。我知道我必须将其反序列化为 aList<obj>但它不起作用。你能帮我吗?

这是我到目前为止所尝试的:

// ListView A (Source)
// the ItemSelected is processed this function is called

public void AddToHistory(Object obj)
{
    string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "history.txt");
    var content = JsonConvert.SerializeObject(obj);
    File.WriteAllText(fileName, content);
}

// ListView B (Destination View)
void CreateListOfObjects()
{
    ObjectList = new List<Object>();
    string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "history.txt");
    var content = File.ReadAllText(fileName);
    var json = JsonConvert.DeserializeObject<Object>(content);
    ObjectList.Add(json);
}

private List<Object> _object;
public List<Object> ObjectList
{
    get => _object;
    set => SetValue(ref _object, value);
}

标签: c#jsonlistview

解决方案


我终于找到了解决方法。现在我首先使用一个 List 来为我的对象数组提供包装器。

// ListView A (Source)
// when ItemSelected is processed this function is called

public void AddToHistory(Object obj)
{
    string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "history.txt");
    var _tempList = new List<Object>();
    if (File.Exist(fileName) 
    {
        var _tempContent = File.ReadAllText(fileName);
        var json = JsonConvert.DeserializeObject<List<Object>>(tempContent);
        _tempList.AddRange(json);
        _tempList.Add(obj);
    } else 
    {
        _tempList.Add(obj);
    }
    var content = JsonConvert.SerializeObject(_tempList);
    File.WriteAllText(fileName, content);
}

// ListView B (Destination View)
void CreateListOfObjects()
{
    ObjectList = new List<Object>();
    string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "history.txt");
    var content = File.ReadAllText(fileName);
    var json = JsonConvert.DeserializeObject<List<Object>>(content);
    ObjectList.AddRange(json);
}

推荐阅读