http://msdn.microsoft.com/zh-cn/library/dd728671%28v=VS.95%29.aspx里面有详细的MS官方的TREEVIEW控件的介绍。我只是谈一谈我接触的treeview的一些收获。
或许我是比较习惯MS的控件以及控件预设的一些属性,被他们开玩笑说不是正宗的程序员,maybe,我不是吧。好了,言归正传。
treeview控件在asp.net和wpf中都有,在asp.net中可以再css文件中设置其样式,同时其各个属性也是发挥着很重要的作用。如果是需要引用css文件,则其格式和其他标签引用的方法是一样,在页面head里面引入css文件,具体到某样式则是:如“cssclass=“wrap””。如果不是导入外部css文件,则是在页面控件中设置各种属性,常见的width,height等等,具体到某控件的特有属性等等。那相对于treeview来说,更多的会关注于RootNodeStyle、ParentStyle、LeafNodeStyle等等。先看一个例子,然后仔细介绍。
<asp:TreeView ID="trPage" runat="server" ShowExpandCollapse="true" CollapseImageUrl="~/images/img08.png" ExpandImageUrl="~/images/img13.png"
ForeColor="#412112" HoverNodeStyle-BackColor="AliceBlue" LeafNodeStyle-CssClass="tex"
RootNodeStyle-BackColor="Aqua" ParentNodeStyle-BackColor="BlanchedAlmond" NodeIndent="0" RootNodeStyle-NodeSpacing="2px" ParentNodeStyle-NodeSpacing="2px"
LeafNodeStyle-BackColor="ButtonShadow" RootNodeStyle-Width="70px" ParentNodeStyle-Width="70px" LeafNodeStyle-Width="60px" LeafNodeStyle-NodeSpacing="2px" LeafNodeStyle-VerticalPadding="5px">
<Nodes>
<asp:TreeNode Text="1" >
<asp:TreeNode Text="11"/>
<asp:TreeNode Text="111" />
</asp:TreeNode>
<asp:TreeNode Text="2">
<asp:TreeNode Text="22" />
<asp:TreeNode Text="222">
<asp:TreeNode Text="2222" />
</asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="3">
<asp:TreeNode Text="33" />
<asp:TreeNode Text="333">
<asp:TreeNode Text="3333">
<asp:TreeNode Text="33333" />
</asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
首先需要设置treeview样式,那基本的tree结构心中是有底的,将若干个treenode嵌套或者堆砌就是一棵tree了,或者将需要用treeview显示的数据binding到treeview上,然后再设计自己想要的样式。或简约或专业,但是都可以根据自己的风格设置。在tree中,结点预设的图片可能不能满足你的要求,那你可以自己设置collapseImageUrl(折叠结点)、ExpandImageUrl(展开结点)、NoExpandImageUrl(不能展开结点)。如:CollapseImageUrl="~/images/img08.png"。接着你就可以开始根据你想要的效果设置其他样式了,比如HoverNodeStyle、SelectedNodeStyle、RootNodeStyle、ParentNodeStyle、LeafNodeStyle、NodeStyle等等,在每一个Style中有可以具体的设置BackColor、BorderStyle、ChildNodePadding、FontStyle等等,当然在treeview中还可以设定各种事件等,这就需要读者自己动手尝试了。
在wpf中,treeview一般会和mvvm模式中的viewmodel相联系,先看一个简单的例子。
<TreeView Name="" Width="250" Padding="0" Margin="0" BorderThickness="1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="" ItemsSource="">
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text=""></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
可以在<Style>中设置样式,如:
<Style TargetType="{x:Type TreeViewItem}"> <Setter Property="IsExpanded" Value="" /> <Setter Property="IsSelected" Value="" /> <Setter Property="FontWeight" Value="Normal" /> </Style>
在WPF中还有一个类似的控件expander,也是可伸缩展开的树形控件,不过它相对来说灵活很多,方向可上可下可左可右。具体可以参考MSDN。
这是开张第一篇,接着周五上班时间的尾巴,就这样收笔吧。