XAML中定义绑定(需要注意的是绑定的节点如果是自己定义的类那么无法设置节点的展开,所以需要在样式中进行设置)
<TreeView Name="tvProperties" Width="250" Padding="0" Margin="0" BorderThickness="1"> <TreeView.ItemContainerStyle > <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="IsExpanded" Value="true" /> <Setter Property="Visibility" Value="{Binding Visible}" /> </Style> </TreeView.ItemContainerStyle> <TreeView.ItemTemplate> <HierarchicalDataTemplate DataType="{x:Type local:PropertyNodeItem}" ItemsSource="{Binding Path=Children}"> <StackPanel Orientation="Horizontal"> <Image Width="20" Height="20" VerticalAlignment="Center" Source="{Binding Icon}" Margin="0,0,2,2"></Image> <TextBlock VerticalAlignment="Center" Text="{Binding DisplayName}"></TextBlock> <Image Width="20" Height="20" VerticalAlignment="Center" Source="{Binding EditIcon}" Margin="2,0,0,0"></Image> <StackPanel.ToolTip> <TextBlock VerticalAlignment="Center" Text="{Binding Name}" TextWrapping="Wrap" MaxWidth="200" ></TextBlock> </StackPanel.ToolTip> </StackPanel> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView>
后台代码:(需要注意如果应用了绑定图片,那么如果图片的路径为空或者不设置图片或者图片的路径不正确的时候那么窗体加载非常慢,务必将不显示图片的节点的图片属性设置为null)
public BitmapImage FOLDER_ICON; public BitmapImage TAG_ICON; public BitmapImage EDITABLE_ICON; public TreeViewBinding() { InitializeComponent(); FOLDER_ICON = new BitmapImage(new Uri("./SysteminfoBlue.bmp", UriKind.Relative)); TAG_ICON = new BitmapImage(new Uri("./SysteminfoBlue.bmp", UriKind.Relative)); EDITABLE_ICON = new BitmapImage(new Uri("./SysteminfoBlue.bmp", UriKind.Relative)); ShowTreeView(); } private void ShowTreeView() { List<PropertyNodeItem> itemList = new List<PropertyNodeItem>(); for (int i = 0; i < 20; i++) { PropertyNodeItem node = new PropertyNodeItem() { DisplayName = "父节点" + i, Name = "节点" + i, Icon = null, EditIcon = new BitmapImage(new Uri("./SysteminfoBlue.bmp", UriKind.Relative)) }; for (int j = 0; j < 4; j++) { PropertyNodeItem node_tag = new PropertyNodeItem() { DisplayName = "Child" + j, Name = "This is the discription of Tag 1. This is a tag.", Icon = TAG_ICON, EditIcon = null }; node.Children.Add(node_tag); } itemList.Add(node); } this.tvProperties.ItemsSource = itemList; }
节点类:(有些例子中将图片属性设置为string类型,如果那么设置那么当节点比较多且某些节点不设置图片的时候窗体加载非常慢)
internal class PropertyNodeItem { public BitmapImage Icon { get; set; } public BitmapImage 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>(); } }
浙公网安备 33010602011771号