我们在WPF-03 资源之Resources结尾中介绍逻辑树和可视化树的基本概念,我们这节来介绍这两棵树
逻辑树(Logical Tree)
逻辑树是由每个控件的节点组成,本质上就是XAML文件中的UI元素,我们可以通过LogicalTreeHelper类提供的静态方法获取逻辑树的对象,我们通过一个例子演示获取整个页面逻辑树
<Window x:Class="Example_10.RepresentLogicalTree"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:Example_10" mc:Ignorable="d" Title="RepresentLogicalTree" Height="450" Width="800"><Grid><Grid.RowDefinitions><RowDefinition Height="0.15*"></RowDefinition><RowDefinition></RowDefinition></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition></ColumnDefinition></Grid.ColumnDefinitions><StackPanel Grid.Row="0" Grid.Column="0" Orientation="Horizontal"><Button Name="btnLogical" Height="30" Click="btnClick_Click">展示逻辑树</Button><Label VerticalAlignment="Center" Margin="200,0,0,0">Label 控件</Label></StackPanel><StackPanel><TreeView Name="logicalTree"></TreeView></StackPanel></Grid>
</Window>
public partial class RepresentLogicalTree : Window{public RepresentLogicalTree(){InitializeComponent();}private void btnClick_Click(object sender, RoutedEventArgs e){logicalTree.Items.Add(GetLogicTree(this));}public static TreeViewItem GetLogicTree(DependencyObject obj){if (obj == null){return null;}TreeViewItem treeNode = new TreeViewItem { Header = obj.GetType().FullName, IsExpanded = true };foreach (var child in LogicalTreeHelper.GetChildren(obj)){var item = GetLogicTree(child as DependencyObject);if (item != null){treeNode.Items.Add(item);}}return treeNode;}}
我们可以很清晰的看到整个逻辑树节点对应到XAML页面中的元素
可视化树(Visual Tree)
可视化树是逻辑树的一种扩展,逻辑树的每个结点都被分解为核心视觉组件,逻辑树节点对我们来说是个黑箱,而视觉树暴露了视觉的实现细节,我们可以通过VisualTreeHelper类提供的静态方法获取可视化树节点,可视化树要比逻辑树呈现的粒度更细,XAML结构和上面结构相同,我们来呈现可视化树结构:
public partial class RepresentVisualTree : Window{public RepresentVisualTree(){InitializeComponent();}private void btnVisual_Click(object sender, RoutedEventArgs e){VisualTree.Items.Add(GetVisualTree(this));}public static TreeViewItem GetVisualTree(DependencyObject obj){if (obj == null){return null;}TreeViewItem treeNode = new TreeViewItem { Header = obj.GetType().FullName, IsExpanded = true };for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++){var child = VisualTreeHelper.GetChild(obj, i);var item = GetVisualTree(child);if (item != null){treeNode.Items.Add(item);}}return treeNode;}}
从上面的例子我们可以看到更细粒度的控件组成部件,下图展示了整个视觉图的组成,绿色表示可视化树,红色表示逻辑树,可视化树范围包含逻辑树
这节我们主要了解WPF中逻辑树和可视化树,通过本节希望能够加深对WPF中控件组成的部件的了解