将所选项目从listView添加到另一个ListView



我想将每个处理过的SelectedItemListView A添加到ListView B作为一种历史记录。如果我仅将其编码为一个对象,但是当我试图将另一个对象添加到ListView B时,它没有显示。我知道我必须将其视为List<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);
}

尝试使用file.appendalltext代替file.writealltext,因为writealltext在写作时会覆盖退出文件。

public void CreateListOfObjects()
    {
        string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "history.txt");
        var content = File.ReadAllText(fileName);
        var itemList = JsonConvert.DeserializeObject<List<string>>(content);
        foreach(var item in itemList)
        {
            listView2.Items.Add(item);
        }
    }

我终于找到了解决方法。现在,我首先要使用列表,以便将包装器用于我的对象数组。

// 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);
}

最新更新