Understanding the Visual Tree and Logical Tree in WPF

The Visual Tree

The visual tree represents all of the elements in your UI which render to an output device (typically, the screen). The visual tree is used for many things like rendering, event routing, locating resources (if an element has no logical parent), and more.

WPF 中除了逻辑树的概念,还存在可视化树的概念。可视化树描述由 Visual 基类表示的可视化对象的结构。为控件编写模板时,将定义或重新定义适用于该控件的可视化树。对于出于性能和优化原因想要对绘图进行较低级别控制的开发人员来说,他们也会对可视化树感兴趣。作为常规 WPF 应用程序编程一部分的可视化树的一个公开情况是,路由事件的事件路由大多数情况下遍历可视化树,而不是逻辑树。这种微妙的路由事件行为可能不会很明显,除非您是控件作者。在可视化树中路由使得在可视化级别实现组合的控件能够处理事件或创建事件 setter。

private void ShowVisualTree(DependencyObject root)

        {

            for(int i=0; i< VisualTreeHelper.GetChildrenCount(root);i++)

            {

                sb += VisualTreeHelper.GetChild(root, i) + "/r/n";

                ShowVisualTree(VisualTreeHelper.GetChild(root, i));

            }

 

        }

The Logical Tree

The logical tree represents the essential structure of your UI. It closely matches the elements you declare in XAML, and excludes most visual elements created internally to help render the elements you declared. WPF uses the logical tree to determine several things including dependency property value inheritance, resource resolution, and more.

逻辑树的存在用途是使内容模型可以容易地循环访问其可能包含的子元素,从而可以对内容模型进行扩展。此外,逻辑树还为某些通知提供了框架,例如当加载逻辑树中的所有元素时。

private void ShowLogicTree(FrameworkElement root)

        {

            foreach (var child in LogicalTreeHelper.GetChildren(root))

            {

                sb += child.ToString()+ "/r/n";

                if(child is FrameworkElement)

                {

                    ShowLogicTree((FrameworkElement)child);

                }

            }

        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值