本文样例通过NuGet获取MvvmLight框架,实现了TreeView的加载,节点添加和节点删除功能,其中节点加载的方式与常见的迭代方式不同,这里使用了字典的方式,提供了一种生成树结构数据对象的方式,如果有遇到TreeView数据加载卡顿的同学,可以考虑尝试使用这种方式。
本文主要代码如下(文章最后可下载源码),
首先定义了树节点接口,包含组成树结构数据的基本属性
public interface ITree<T>
{
string TreeId { get; }
string TreePid { get; }
ObservableCollection<T> Children { get; set; }
}
之后再定义Model,继承并实现接口
public class TreeModel : ObservableObject, ITree<TreeModel>
{
public string TreeId { get { return Id; } }
public string TreePid { get { return Pid; } }
private ObservableCollection<TreeModel> _Children;
public ObservableCollection<TreeModel> Children
{
get { return _Children; }
set
{
_Children = value;
RaisePropertyChanged(() => Children);
}
}
public string Id { get; set; }
public string Pid { get; set; }
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
RaisePropertyChanged(() => Name);
}
}
private bool _IsSelect;
public bool IsSelect
{
get { return _IsSelect; }
set
{
_IsSelect = value;
RaisePropertyChanged(() => IsSelect);
}
}
public static List<TreeModel> GetTreeModels()
{
var data = new List<TreeModel>();
var rootCount = 200;
var nodeCount = 50000;
for (int i = 0; i < rootCount; i++)
{
data.Add(new TreeModel()
{
Id = "root" + i.ToString(),
Name = "root" + i.ToString(),
});
}
for (int i = 0; i < nodeCount; i++)
{
data.Add(new TreeModel()
{
Id = "node" + i.ToString(),
Pid = "root" + (i % rootCount).ToString(),
Name = "node" + i.ToString(),
});
}
return data;
}
}
在定义ViewModel之前,先封装了一个字典Helper
public class DicHelper<Key, Value>
{
public Dictionary<Key, Value> DicData { get; set; }
public DicHelper()
{
DicData = new Dictionary<Key, Value>();
}
public bool AddItem(Key key, Value value)
{
if (key == null || value == null || ContainsKey(key))
{
return false;
}
DicData.Add(key, value);
return true;
}
public void RemoveItem(Key key)
{
DicData.Remove(key);
}
public Value GetItem(Key key)
{
return ContainsKey(key) ? DicData[key] : default(Value);
}
public List<Value> GetItems()
{
return DicData.Values.ToList();
}
public bool ContainsKey(Key key)
{
if (key == null)
{
return false;