LISTING 3.1 A Simple About Dialog in XAML FIGURE 3.1 The rendered dialog from Listing 3.1.Logical and Visual Trees
Title="About WPF Unleashed" SizeToContent="WidthAndHeight"
Background="OrangeRed">
product.
FIGURE 3.2 The logical tree for Listing 3.1.
Not all logical tree nodes appear in the visual tree; only the elements that derive from System.Windows.Media.Visual or System.Windows.Media.Visual3D are included. Other elements (and simple string content, as in Listing 3.1) are not included because they don't have inherent rendering behavior of their own.
Figure 3.3 illustrates the default visual tree for Listing 3.1 when running on Windows Vista with the Aero theme. This diagram exposes some inner components of the UI that are currently invisible, such as the ListBox's two ScrollBars and each Label's Border. It also reveals that Button, Label, and ListBoxItem are all comprised of the same elements, except Button uses an obscure ButtonChrome element rather than a Border. (These controls have other visual differences as the result of different default property values. For example, Button has a default Margin of 10 on all sides whereas Label has a default Margin of 0.)
TIP XamlPad contains a button in its toolbar that reveals the visual tree (and property values) for any XAML that it renders. It doesn't work when hosting a Window (as in Figure 3.1), but you can change the Window element to a Page (and remove the SizeToContent property) to take advantage of this functionality.
Because they enable you to peer inside the deep composition of WPF elements, visual trees can be surprisingly complex. Fortunately, although visual trees are an essential part of the WPF infrastructure, you often don't need to worry about them unless you're radically restyling controls (covered in Chapter 10, "Styles, Templates, Skins, and Themes") or doing low-level drawing (covered in Chapter 11, "2D Graphics"). Writing code that depends on a specific visual tree for a Button, for example, breaks one of WPF's core tenets—the separation of look and logic. When someone restyles a control like Button using the techniques described in Chapter 10, its entire visual tree is replaced with something that could be completely different.

No comments:
Post a Comment