WPF getting started tutorial series 13-dependency attributes (III), wpf getting started tutorial

Source: Internet
Author: User

WPF getting started tutorial series 13-dependency attributes (III), wpf getting started tutorial

Iv. Read-Only dependency attributes

In the past, for non-WPF functions, the encapsulation of class attributes often encapsulates the fields that wish to be exposed to external read-only operations as read-only attributes, the concept of read-only attributes is also provided in WPF. For example, dependency attributes of some WPF controls are read-only, which are often used to report the status and information of controls, such as IsMouseOver and other attributes, it makes no sense to assign a value to it at this time. You may also have the question: why not use the general. Net attribute to provide it? Can an attribute be bound to an element? This is because the read-only dependency attribute, such as Trigger, must be used in some places. It is also because multiple internal providers may modify its value. net properties cannot complete the tasks of the day.
How to Create a read-only dependency attribute? In fact, creating a read-only dependency attribute is similar to creating a general dependency attribute. The difference is that DependencyProperty. Register is changed to DependencyProperty. RegisterReadOnly. Like the preceding common dependency property, it returns a DependencyPropertyKey. In addition, only one GetValue is provided to the external, so that it can be used like a general attribute, but it cannot be set externally.

The following is a simple example:

Public partial class WindowReadOnly: Window {public WindowReadOnly () {InitializeComponent (); // set the value DispatcherTimer timer = new DispatcherTimer (TimeSpan. fromSeconds (1), DispatcherPriority. normal, (object sender, EventArgs e) =>{ int newValue = Counter = int. maxValue? 0: Counter + 1; SetValue (counterKey, newValue) ;}, Dispatcher);} // attribute wrapper, only GetValue public int Counter {get {return (int) is provided) getValue (counterKey. dependencyProperty) ;}}// use RegisterReadOnly instead of Register to Register a read-only dependency attribute private static readonly DependencyPropertyKey counterKey = DependencyProperty. registerReadOnly ("Counter", typeof (int), typeof (WindowReadOnly), new PropertyMetadata (0 ));}

 

 


XAML code:

<Window x:Name="winReadOnly" x:Class="WpfApp1.WindowReadOnly"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  Title="WindowDepend" Height="300" Width="300">    <Grid>        <Viewbox>            <TextBlock Text="{Binding ElementName=winReadOnly, Path=Counter}" />        </Viewbox>    </Grid></Window>

 

 

Shows the effect:

 

5. Additional attributes

Now we will continue to explore another special dependency property-additional property. An additional property is a special dependency property. This is one of the features of WPF. in a general sense, you also have this attribute because you have a relationship with others.

An additional attribute means that an attribute does not belong to a certain object, but is subsequently attached to an object due to a certain requirement, that is to say, the attributes that an object has after being put into a specific environment are called additional attributes. The function of additional attributes is to decouple attributes from data types, so that the design of data types is more flexible, for example, when a TextBox is placed in a different layout container, there will be different layout attributes. These attributes are appended by the layout container as the TextBox. The nature of the additional attributes is the dependency attribute, the two are only slightly different in the registration and package.

An additional property is a special form of dependency property. It allows you to set attributes of other elements in an element. In general, an additional attribute is used for a parent element to locate other element la S. Just like the Grid and DockPanel elements contain additional attributes. Grid uses additional attributes to specify specific rows and columns containing child elements, while DockPanel uses additional attributes to specify where the child elements should be docked in the panel.

You do not have this additional attribute and need to append it in some contexts. For exampleStackPanelGrid. Row attribute, if we defineStackPanelIt makes no sense to define a Row attribute for a class, because we do not know that it will definitely be placed in the Grid, which leads to waste.

For example, the following definition of the transfer control uses the Row attribute of the Grid to locate itself to a specific Row.

   <Grid>        <Grid.RowDefinitions>            <RowDefinition Height="101*"/>            <RowDefinition Height="80"/>            <RowDefinition Height="80"/>        </Grid.RowDefinitions>        <StackPanel Grid.Row="0" >

 

 

Although it is not necessary for a common WPF developer to understand dependencies and additional attributes, mastering the overall running mechanism of the WPF system is very important to improve the WPF application technology.

By using additional attributes, you can avoid encoding conventions that may prevent different objects in a link from passing information at runtime. You can set attributes for common basic classes so that each object only needs to obtain and set this attribute. However, you may want to do this in many cases, which will fill your base class with a large number of shared attributes. It may even introduce the following situation: only two of the hundreds of offspring attempt to use one attribute. Such classes are poorly designed. To solve this problem, we use the additional attribute concept to allow an object to assign values to properties not defined by its own class structure. After creating related objects in the object tree, read this value from the sub-object at runtime.

The best example is layout panel. Each layout panel needs its own unique way to organize its child elements. For example, the Canvas needs Top and left layout, and the DockPanel needs the Dock layout. Of course, you can also write your own layout panel (in the previous article, we have carefully discussed the layout. If you have any unclear friends, you can review it again ).

The buttons in the following code use Canvas. Top and Canvas. Left = "20" of Canvas to locate the layout. These two are the legendary additional attributes.

<Canvas>    <Button Canvas.Top="20" Canvas.Left="20" Content="Knights Warrior!"/></Canvas> 

 

The method for defining additional properties is the same as that for defining dependency properties. Previously we used DependencyProperty. Register to Register a dependency property, but the RegisterAttach () method was used when registering the property. The RegisterAttached parameter is exactly the same as the Register parameter. So where does the concept of Attached come from?

In fact, we use the dependency attribute, which is always being Attached ). We register (construct) a dependency attribute, and then use GetValue and SetValue in DependencyObject to operate on this dependency attribute, that is, we associate this dependency attribute to this DependencyObject through this method, it is achieved by encapsulating CLR attributes. What about RegisterAttached?

Next, let's look at the simplest application: First, we register (construct) an additional attribute.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. windows; using System. windows. media; namespace WpfApp1.Services {public class TurnoverManager: DependencyObject {// exposes the read Operation public static double GetAngle (DependencyObject obj) {return (double) obj in the form of a static method. getValue (AngleProperty);} // exposes the write operation public static void SetAngle in the form of a static method (DependencyObject obj, double value) {obj. setValue (AngleProperty, value);} // register an additional Property public static readonly DependencyProperty AngleProperty = DependencyProperty by using RegisterAttached. registerAttached ("Angle", typeof (double), typeof (TurnoverManager), new PropertyMetadata (0.0, OnAngleChanged); // when the value in the attached property changes, rotate the corresponding angle. Private static void OnAngleChanged (DependencyObject obj, DependencyPropertyChangedEventArgs e) {var element = obj as UIElement; if (element! = Null) {element. RenderTransformOrigin = new Point (0.5, 0.5); element. RenderTransform = new RotateTransform (double) e. NewValue );}}}}

 

Then, we use this custom additional property in the program.

<Window x: Class = "WpfApp1.WindowTurnover" xmlns =" http://schemas.microsoft.com/winfx/2006/xaml /Presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "Xmlns: local =" clr-namespace: WpfApp1.Services "Title =" WindowTurnover "Height =" 400 "Width =" 500 "Loaded =" Window_Loaded "> <Grid. rowDefinitions> <RowDefinition Height = "313 *"/> <RowDefinition Height = "57 *"/> </Grid. rowDefinitions> <Canvas Grid. row = "0"> <Ellipse Name = "ellipseRed" Fill = "Red" Width = "100" Height = "60" Canvas. left = "56" Canvas. top = "98" local: TurnoverManager. angle = "{Binding ElementName = sliderAngle, Path = Value}"/> <Rectangle Name = "ellipseBlue" Fill = "Blue" Width = "80" Height = "80" Canvas. left = "285" Canvas. top = "171" local: TurnoverManager. angle = "45"/> <Button Name = "btnWelcome" Content = "Welcome to" Canvas. left = "265" Canvas. top = "48" FontSize = "20" local: TurnoverManager. angle = "60"/> </Canvas> <WrapPanel Grid. row = "1"> <Label Content = "angle size"/> <Slider x: name = "sliderAngle" Minimum = "0" Maximum = "240" Width = "300"/> </WrapPanel> </Grid> </Window>

In XAML, you can use the additional attributes registered (constructed) just now: for example.

By adjusting the angle value, different effects are shown in the following two figures. Figure 1, Figure 2.

 

Figure 1

 

Figure 2

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.