WPF 4 unleashed / Adam Nathan. p. cm. Includes index. ISBN 0. 1. Windows presentation foundation. 2. Application software. 3. Microsoft. WPF 4 goudzwaard.info - Mehmet Akif SÖNMEZ. Pages·· MB·43 Downloads. Nathan, Adam. WPF 4 unleashed / Adam Nathan. p. cm. Includes. “I found Windows Presentation Foundation Unleashed to be an excellent and “ Windows Presentation Foundation Unleashed is the book that made WPF make.
|Language:||English, Spanish, Arabic|
|Distribution:||Free* [*Registration Required]|
Contribute to adamshe/books development by creating an account on GitHub. Source: Adam Nathan “Windows Presentation Foundation Unleashed”, SAMS Publishing Developing applications with C#, WPF, and XAML. Pro WPF in C# is a thorough, authoritative guide to how WPF really works. Understand the fundamentals of WPF programming, from XAML to controls and.
Because just about every dialog from Listing 3. For example, property values are sometimes propa- gated down the tree to child elements automatically, and raised events can travel up or down the tree. This behavior of property values is discussed later in this chapter, and this behavior of events is discussed in Chapter 6.
The logical tree exposed by WPF is a simplification of what is actually going on when the elements are rendered. You can think of the visual tree as an expansion of a logical tree, in which nodes are broken down into their core visual components. For example, although a ListBox is logically a single control, its default visual representation is composed of more primitive WPF elements: Not all logical tree nodes appear in the visual tree; only the elements that derive TIP from System.
Visual3D are XamlPadX tool mentioned in the preceding included. Other elements and simple chapter, have functionality for exploring the 3 string content, as in Listing 3. 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.
Because they enable you to peer inside the deep composition of WPF elements, visual trees can be surprisingly complex. However, you can easily traverse both the logical and visual trees using the somewhat symmetrical System. LogicalTreeHelper and System.
VisualTreeHelper classes. This requires adding x: Diagnostics; using System. Windows; using System. Media; public partial class AboutDialog: TIP Visual trees like the one represented in Figure 3. The term visual tree is then used to describe any subtree that contains visual-only illogical? In Figure 3. This enables you to navigate and visualize the visual tree.
Navigating either tree can sometimes be done with instance methods on the elements themselves. FrameworkElement, the common base class for controls such as Button and Label, and its peer FrameworkContentElement both define a public Parent property representing the logical parent and a protected LogicalChildren property for the logical children. Subclasses of these two classes often publicly expose their logical chil- dren in a variety of ways, such as in a public Children collection.
Some classes, such as Button and Label, expose a Content property and enforce that the element can have only one logical child. Dependency Properties WPF introduces a type of property called a dependency property that is used throughout the platform to enable styling, automatic data binding, animation, and more. You might first meet this concept with skepticism, as it complicates the picture of. NET types having simple fields, properties, methods, and events.
But when you understand the problems that dependency properties solve, you will likely accept them as a welcome addition.
Dependency Properties 63 A dependency property depends on multiple providers for determining its value at any point in time. These providers could be an animation continuously changing its value, a parent element whose property value propagates down to its children, and so on.
Arguably the biggest feature of a dependency property is its built-in ability to provide change notification. The motivation for adding such intelligence to properties is to enable rich functionality directly from declarative markup. Button, for example, has more than public properties most of which are inherited from Control and its base classes!
Properties can be easily set in XAML directly or by using a design tool without any procedural code. But without the 3 extra plumbing in dependency properties, it would be hard for the simple action of setting properties to get the desired results without the need to write additional code. In this section, we briefly look at the implementation of a dependency property to make this discussion more concrete, and then we dig deeper into some of the ways that depen- dency properties add value on top of plain.
NET properties: Change notification. Property value inheritance. Support for multiple providers Understanding most of the nuances of dependency properties is usually important only for custom control authors. However, even casual users of WPF need to be aware of what dependency properties are and how they work.
For example, you can only style and animate dependency properties. After working with WPF for a while, you might find yourself wishing that all properties would be dependency properties! A Dependency Property Implementation In practice, dependency properties are just normal.
DependencyProperty class. By convention, all DependencyProperty fields are public, static, and have a Property suffix. Several pieces of infrastructure require that you follow this convention: Dependency properties are usually created by calling the static DependencyProperty. Register method, which requires a name IsDefault , a property type bool , and the type of the class claiming to own the property Button. Optionally via different overloads of Register , you can pass metadata that customizes how the property is treated by WPF, as well as callbacks for handling property value changes, coercing values, and validating values.
Button calls an overload of Register in its static constructor to give the dependency property a default value of false and to attach a dele- gate for change notifications. Finally, the traditional. DependencyObject, the low-level base class from which all classes with dependency properties must derive. GetValue returns the last value passed to SetValue or, if SetValue has never been called, the default value registered with the property. The IsDefault.
But the. NET defining one much faster than doing all the property makes programmatic reading typing yourself! Dependency Properties 65 and writing of the property much more natural for consumers, and it enables the prop- erty to be set via XAML.
This is primarily because dependency properties were invented before. NET generics were widely used. On the surface, Listing 3. However, because GetValue and SetValue internally use an efficient sparse storage system and because IsDefaultProperty is a static field rather than an instance field , the dependency property implementation saves per-instance memory compared to a typical.
NET property. If all the properties on WPF controls were wrappers around instance fields as most. NET properties are , they would consume a significant amount of memory because of all the local data attached to each instance. Having more than fields for each Button, more than fields for each Label, and so forth would add up quickly! The benefits of the dependency property implementation extend to more than just memory usage, however.
The implementation centralizes and standardizes a fair amount of code that property implementers would have to write to check thread access, prompt the containing element to be re-rendered, and so on.
AffectsRender flag to an overload of DependencyProperty. These actions can be re-rendering the appropriate elements, updating the current layout, refreshing data bind- ings, and much more.
One of the interesting features enabled by this built-in change notification is property triggers, which enable you to perform your own custom actions when a property value changes, without writing any procedural code. Without property triggers, you can attach two event handlers to each Button, one for its MouseEnter event and one for its MouseLeave event: The following concise Trigger object is just about all you need: This is automatically done by WPF!
The only trick is assigning this Trigger to each Button. You can apply them only inside a Style object, so an in-depth examination of property triggers is saved for Chapter In the meantime, to experiment with property triggers, you can apply the preceding Trigger to a Button by wrapping it in a few inter- mediate XML elements, as follows: A data trigger is a 3 form of property trigger that works for all.
NET properties not just dependency proper- ties , also covered in Chapter An event trigger enables you to declaratively specify actions to take when a routed event covered in Chapter 6 is raised.
Unfortunately, this collection can only contain event triggers, so its name and type are misleading. Attempting to add a property trigger or data trigger to the collection causes an exception to be thrown at runtime. A simple example of this can be seen in Listing 3.
Notice that the Window auto- matically resizes to fit all the content thanks to its slick SizeToContent setting! This affects even the Buttons and ListBoxItems, which are three levels down the logical tree. Notice that the text in the StatusBar is unaffected by either of these values, despite the fact that it supports these two properties just like the other controls. The behavior of property value inheritance can be subtle in cases like this for two reasons: Not every dependency property participates in property value inheritance.
Internally, dependency properties can opt in to inheritance by passing FrameworkPropertyMetadataOptions. Inherits to DependencyProperty. There may be other higher-priority sources setting the property value, as explained in the next section. In this case, the latter reason is to blame.
A few controls, such as StatusBar, Menu, and ToolTip, internally set their font properties to match current system settings. This way, users get the familiar experience of controlling their font via Control Panel.
For example, if you add a Button as a logical child of the StatusBar in Listing 3. Support for Multiple Providers WPF contains many powerful mechanisms that independently attempt to set the value of dependency properties.
Without a well-defined mechanism for handling these disparate property value providers, the system would be a bit chaotic, and property values could be unstable.
Of course, as their name indicates, dependency properties were designed to depend on these providers in a consistent and orderly manner. This process happens automatically, thanks to the built-in change notification in dependency properties. Step 1: Determine the Base Value Most of the property value providers factor into the base value calculation.
The following list reveals the ten providers that can set the value of most dependency properties, in order from highest to lowest precedence: Local value 2.
Parent template trigger 3. Parent template 4. Style triggers 5. Style setters 7. Theme style triggers 8. Theme style setters 9. Property value inheritance Local value 1 technically means any call to DependencyObject. SetValue, but this is typically seen with a simple property assignment in XAML or procedural code because of the way dependency properties are implemented, as shown previously with Button. Default value 10 refers to the initial value registered with the dependency property, which naturally has the lowest precedence.
The other providers, which all involve styles and templates, are explained further in Chapter Although this has precedence over property value inheritance 9 , you can still override these font settings using any mechanism with a higher precedence, such as simply setting local values on StatusBar.
GetValueSource method as a debugging aid. This returns a ValueSource structure that contains a few pieces of data: When calling this method on the StatusBar instance from Listing 3. Theme styles are sometimes referred to as default styles. The enumeration value for a theme style trigger is DefaultStyleTrigger.
Do not use this method in production code! In addition, treating a property value differently, depend- ing on its source, goes against the way things are supposed to work in WPF applications. If the theme is changed and the new theme tries to change the default Foreground color or if other providers with higher precedence try to do the same , this change is trumped by the local setting of black.
Fortunately, DependencyObject provides exactly this kind of mechanism with its ClearValue method. This can be called on a Button b as follows in C: ClearValue Button. ForegroundProperty ; Button. ForegroundProperty is the static DependencyProperty field. After calling ClearValue, the local value is simply removed from the equation when WPF recalculates the base value.
A trigger is either active or inactive, and when it is inactive, it is simply ignored in the property value calculation. Step 2: Evaluate If the value from step one is an expression an object deriving from System.
Expression , WPF performs a special evaluation step to convert the expression into a concrete result. Step 3: Apply Animations If one or more animations are running, they have the power to alter the current property value using the value after step 2 as input or completely replace it. Therefore, anima- tions the topic of Chapter 17 can trump all other property value providers—even local values!
This is often a stumbling block for people who are new to WPF. Step 4: Coerce After all the property value providers have had their say, WPF passes the almost-final property value to a CoerceValueCallback delegate, if one was registered with the depen- dency property.
The callback is responsible for returning a new value, based on custom logic. For example, built-in WPF controls such as ProgressBar use this callback to constrain its Value dependency property to a value between its Minimum and Maximum values, returning Minimum if the input value is less than Minimum and Maximum if the input value is greater than Maximum.
If you change your coercion logic at runtime, you can call CoerceValue to make WPF run the new coercion and validation logic again. Validate Finally, the potentially coerced value is passed to a ValidateValueCallback delegate, if one was registered with the dependency property. This callback must return true if the input value is valid and false otherwise. Returning false causes an exception to be thrown, canceling the entire process.
TIP DependencyObject has a SetCurrentValue method that directly updates the current value of a property without changing its value source.
The value is still subject to coercion and validation. This is meant for controls that set values in response to user interaction. For example, the RadioButton control modifies the value of the IsChecked property on other RadioButtons in the same group, based on user interaction.
Attached Properties An attached property is a special form of dependency property that can effectively be attached to arbitrary objects. This may sound strange at first, but this mechanism has several applications in WPF. Instead, you must use the FontSize and FontStyle attached properties that happen to be defined on a class called TextElement. This enables the desired property value inheritance, as shown in Figure 3. FontSize and TextElement. When a XAML parser or compiler encounters this syntax, it requires that TextElement sometimes called the attached property provider have static methods called SetFontSize and SetFontStyle that can set the value accordingly.
Therefore, the StackPanel declaration in Listing 3. SetFontStyle panel, FontStyles. Italic ; set on both Buttons via inheri- panel. Horizontal; tance from the inner StackPanel. Add helpButton ; panel. Add okButton ; Notice that the enumeration values such as FontStyles. Italic, Orientation. Horizontal, and HorizontalAlignment. This is possible thanks to the EnumConverter type converter in the. NET Framework, which can convert any case-insensitive string.
One of the interesting things about the attached property abstraction is that no. NET property is a part of it! SetValue method that a normal dependency property accessor calls, but on the passed-in DependencyObject rather than the current instance: SetValue TextElement. GetValue method: GetValue TextElement. Instead, they are defined by the seemingly unrelated TextElement class and also by the TextBlock class, which could alternatively be used in the preceding examples.
How can this possibly work when TextElement. FontSizeProperty and TextElement. FontStyleProperty is separate from Control. The key is the way these dependency properties are internally registered.
If you were to look at the source code for TextElement, you would see something like the following: Inherits FrameworkPropertyMetadataOptions.
Dependency Properties 75 Continued Control.
Inherits ; Therefore, the FontSize, FontStyle, and other font-related dependency properties inherited by all controls are the same properties exposed by TextElement! Fortunately, in most cases, the class that exposes an attached property the GetXXX and SetXXX methods is the same class that defines the normal dependency property, avoiding this confusion.
Object intended for storing arbitrary custom data with each instance. But attached properties are a more powerful and flexible mechanism for attaching custom data to any object deriving from DependencyObject. A further twist to the story of attached properties is that although setting them in XAML relies on the presence of the static SetXXX method, you can bypass this method in proce- dural code and call DependencyObject.
This means that you can use any dependency property as an attached property in procedural code. SetValue ItemsControl. There are more interesting ways to extend elements in this manner. SetValue FrameworkElement. Various Panel-derived classes define attached properties designed to be attached to their children for controlling how they are arranged. This way, each Panel can apply its own custom behavior to arbitrary children without requiring all possible child elements to be burdened with their own set of relevant properties.
It also enables systems such as layout to be easily extensible, because anyone can write a new Panel with custom attached prop- erties. The WPF team could have exposed its features via typical. Instead, the team added several fundamental concepts that enable a wide range of features to be exposed in a way that can provide great produc- tivity for developers and designers. There are multiple types of properties, multiple trees, and multiple ways of achieving the same results such as writing declara- tive versus procedural code!
Hopefully you can now appreciate some of the value of these new mechanisms. Throughout the rest of the book, these concepts generally fade into the background as we focus on accomplishing specific development tasks.
TransformToAncestor method, Visual3D. TransformToAncestor method, explained, Visual3D. TransformToAncestor method, geometries aggregate geometries, Visual3D. Email us at indexes samspublishing. See data binding BezierSegment class, Binding.
See also SimpleCanvas How can we make this index more useful? See also specific commands containers built-in commands, Expander class, controls with built-in command bindings, Frame class, How can we make this index more useful?
NET properties, rendering, controlling binding to collections, data templates, binding to entire objects, explained, binding to UIElement, string formatting, ElementName property, value converters, INotifyDataErrorInfo interface, troubleshooting, IsAsync property, WPF 3.
See specific directives DrawingBrush class, , DirectX DrawingContext class development of, 8 clip art example, versus WPF, methods, when to use, DrawingImage class, WPF interoperability, 13, drawings discrete keyframes, clip art example, Dismissed event, Drawing class, DispatcherObject class, 56 DrawingBrush class, DispatcherPriority enumeration, DrawingContext methods, How can we make this index more useful?
See trees DrawingVisual class, ElementHost class, geometries. See releases of WPF event wrappers, ExceptionValidationRule object, JumpItemsRejected, Execute method, JumpItemsRemovedByUser, executing commands with input gestures, keyboard events, Expander class, mouse events Expansion property ManipulationDelta class , capturing, explicit sizes, avoiding, 79 drag-and-drop events, explicit versus implicit runs, explained, ExponentialEase function, MouseButtonEventArgs, Expression Blend, 12 MouseEventArgs, expressions, 71 MouseWheelEventArgs, ExtendGlassFrame method, transparent and null regions, extensibility mechanisms, attached properties as, 75 navigation events, How can we make this index more useful?
Successfully reported this slideshow. We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime. Upcoming SlideShare. Like this presentation? Why not share! An annual anal Embed Size px.
Start on. Show related SlideShares at end. WordPress Shortcode.