转自:https://www.cnblogs.com/izualx/archive/2011/02/03/1949055.html
最近在用WPF做开发,项目进展的还算顺利,WPF总体来说还是比较方便的,其中变化最大的主要是Listview和Treeview控件,而且TreeView似乎在WPF是一个备受指责的控件,很多人说他不好用。其实我觉得是开发人员没有掌握好WPF中所传承的MVC思想。在View方面,WPF中的TreeView给了开发人员更大的灵活性,开发人可以非常简单定制每个Node乃至整棵树的外形。同时新的TreeView可以接受各种Collection作为ItemSource,非常灵活。只要简单地了解这些新加入的概念,开发起来就可以得心应手。
首先一个简单的Demo
如果这实现这个Demo呢?我们从MVC三个方面入手:
TreeView的View
在WPF的TreeView,你可以定制每个节点的显示方式,包括为一个节点添加多个图标,这些都只需要在XAML中配置,而不必留下复杂的C#代码。例如:
<TreeView x:Name="treeView" HorizontalAlignment="Left" Height="220.27" Margin="10,10,0,0" VerticalAlignment="Top" Width="498.4">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:PropertyNodeItem}" ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Icon}" Width="20"/>
<TextBlock Text="{Binding DisplayName}"/>
<Image Source="{Binding EditIcon}" Width="20"/>
<StackPanel.ToolTip>
<TextBlock Text="{Binding Name}"/>
</StackPanel.ToolTip>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
在这里我定义了一个简单的TreeView,每个节点对应的DataType是PropertyNodeItem(稍后,我会给出它的定义),每个节点的内容包括:
- ICON:每个节点的首先会显示一个ICON
- DisplayName:每个节点上的文字(这里的文字仅显示一个大概内容,详细内容会在ToolTip中显示)
- Editable ICON:如果一个节点是可以编辑的,我会在节点后面再显示一个Edit ICON
- ToolTip:当鼠标移动到上面时会显示,宽度200PX,自动换行。
TreeView的Model
这里就是刚才说讲到的PropertyNodeItem的定义
internal class PropertyNodeItem
{
public string Icon { get; set; }
public string EditIcon { get; set; }
public string DisplayName { get; set; }
public string Name { get; set; }
public List<PropertyNodeItem> Children { get; set; }
public PropertyNodeItem()
{
Children = new List<PropertyNodeItem>();
}
}
其中Children里面保存的是子节点。在刚才的View里面,我们把HierarchicalDataTemplate的ItemSource定义为PropertyNodeItem的Children熟悉,这样只要Children不为空,TreeView就会继续渲染Children中的对象,并且递归下去。
TreeView的Controller
这里的Controller,我写在xaml.cs里面:
private const string FOLDER_ICON = @"";//Icon路径
private const string EDITABLE_ICON = @"";//Icon路径
private const string TAG_ICON = @"";//Icon路径
private void ShowTreeView()
{
List<PropertyNodeItem> itemList = new List<PropertyNodeItem>();
PropertyNodeItem node1 = new PropertyNodeItem()
{
DisplayName = "Node No.1",
Name = "This is the discription of Node1. This is a folder.",
Icon = FOLDER_ICON,
};
PropertyNodeItem node1tag1 = new PropertyNodeItem()
{
DisplayName = "Tag No.1",
Name = "This is the discription of Tag 1. This is a tag.",
Icon = TAG_ICON,
EditIcon = EDITABLE_ICON
};
node1.Children.Add(node1tag1);
PropertyNodeItem node1tag2 = new PropertyNodeItem()
{
DisplayName = "Tag No.2",
Name = "This is the discription of Tag 2. This is a tag.",
Icon = TAG_ICON,
EditIcon = EDITABLE_ICON
};
node1.Children.Add(node1tag2);
itemList.Add(node1);
PropertyNodeItem node2 = new PropertyNodeItem()
{
DisplayName = "Node No.2",
Name = "This is the discription of Node2. This is a folder.",
Icon = FOLDER_ICON,
};
itemList.Add(node2);
treeView.ItemsSource = itemList;
}
}
以上的代码非常简单,这里就不详加解释了