Dependency properties for Windows Phone 7)

Source: Internet
Author: User

Dependency Properties)

If you want to create a custom control class and define new attributes for the class, or you want to set binding for those attributes, or you want to use animations for these attributes, you need to set these attributes to dependency properties ).

Next, let's take a look at a simple example. We can customize a class, inherit from the button, that is, we make a button ourselves, and define two attributes color1 and color2 for it. The Code is as follows:

public class MyButton : Button    {        public MyButton()        {                    }        private Color _forceColor;        public Color ForceColor        {            get            {                return _forceColor;            }            set            {                _forceColor = value;                this.Foreground = new SolidColorBrush() { Color = _forceColor};            }        }        private Color _backColor;        public Color BackColor        {            get            {                return _backColor;            }            set            {                _backColor = value;                this.Background = new SolidColorBrush() { Color = _backColor };            }        }    }

A button is defined above, and two attributes color1 and color2 are declared. When the set value is set for the color1 attribute, the value is assigned to the foreground color foreground. When the set value is set for the color2 attribute, at the same time, assign the value to the background color background,
Add the namespace xmlns: Local = "CLR-namespace: dependencyproperties" to the current project in mainpage"

Add a mybutton to the page and set forcecolor and backcolor by enumeration:

<Local: mybutton backcolor = "red" forcecolor = "black" content = "mybutton1"> </local: mybutton>

Add Resource

<Color x: Key = "myforcecolor"> Red </color>
<Color x: Key = "mybackcolor"> White </color>

Add a mybutton on the page and set the forcecolor and backcolor values to the resources defined above.

<Local: mybutton backcolor = "{staticresource mybackcolor}" forcecolor = "{staticresource myforcecolor}" content = "mybutton2"> </local: mybutton>

Run the program as follows:

The above is the expected result. Now we use style to set the forcecolor and backcolor values and define resources.

The above shows the effect in the code editor when I define the resource. See the error message and check the error window.

You have not set the object reference to the instance of the object. What is the problem,

Add a mybutton on the page and use the style defined above

<Local: mybutton style = "{staticresource mystyle}" content = "mybutton3"> </local: mybutton>

Run it.

Debugging is also acceptable. Why? This is what I mentioned earlier. To use style for custom attributes, you must set it as dependencyproperty.

The dependencyproperty Definition Format is

Public static readonly dependencyproperty variable name =
Dependencyproperty. Register ("property name ",
Typeof (attribute type ),
Typeof (type of the class ),
New propertymetadata (default value, method triggered when the value changes ));

Now we modify the previous Code and set forcecolor and backcolor to dependencyproperty. The modified mybutton class is as follows:

public class MyButton : Button    {        public MyButton()        {        }        public static readonly DependencyProperty ForceColorProperty =            DependencyProperty.Register("ForceColor",            typeof(Color),            typeof(MyButton),            new PropertyMetadata(Colors.Black, OnColorChanged));        public static readonly DependencyProperty BackColorProperty =            DependencyProperty.Register("BackColor",            typeof(Color),            typeof(MyButton),            new PropertyMetadata(Colors.White, OnColorChanged));        public Color ForceColor        {            set { SetValue(ForceColorProperty, value); }            get { return (Color)GetValue(ForceColorProperty); }        }        public Color BackColor        {            set { SetValue(BackColorProperty, value); }            get { return (Color)GetValue(BackColorProperty); }        }        static void OnColorChanged(DependencyObject obj,            DependencyPropertyChangedEventArgs args)        {            var btn = obj as MyButton;            if (args.Property == ForceColorProperty)            {                btn.Foreground = new SolidColorBrush() { Color = (Color)args.NewValue };            }            if (args.Property == BackColorProperty)            {                btn.Background = new SolidColorBrush() { Color = (Color)args.NewValue };            }        }    }

Now let's take a look at the previously defined style.

No error is reported. Run the program as follows:

Now we know the importance of dependencyproperty.

 

I would like to explain some problems for beginners and understand how to bypass them.

In the above example, dependencyproperty is defined to use static and readonly, Which means we cannot directly use "=" to copy for it, but also static variables rather than instance variables. All the attributes common to mybutton, and the above oncolorchanged are also static and all are static. So we guess that if their values are set, isn't that the attributes of all mybuttons changed, that is definitely not the result we want. Let's take a look at whether things are as bad as we think.

Add a style again, add a mybutton, and use the secondary Style

<Style X: Key = "mystyle2" targettype = "Local: mybutton">
<Setter property = "backcolor" value = "yellow"> </setter>
<Setter property = "forcecolor" value = "black"> </setter>
</Style>

<Local: mybutton style = "{staticresource mystyle2}" content = "mybutton4"> </local: mybutton>

Run the command to check the effect.

This is not a bad result of our conjecture, but an exciting and satisfactory result. The key to this is the oncolorchanged parameter and method body. Be patient, let's take a look at the complete oncolorchanged

static void OnColorChanged(DependencyObject obj,            DependencyPropertyChangedEventArgs args)        {            var btn = obj as MyButton;            if (args.Property == ForceColorProperty)            {                btn.Foreground = new SolidColorBrush() { Color = (Color)args.NewValue };            }            if (args.Property == BackColorProperty)            {                btn.Background = new SolidColorBrush() { Color = (Color)args.NewValue };            }        }

We can see that there are two parameters, the first parameter is the current, using the Instance Object mybutton of the property, the second parameter is but the value set before
We can get it and set the corresponding attributes. This way, although it is a static variable, it will not affect other instances.

Look at the foreground attribute of the button. The official definition is public brush foreground {Get; set;}, so it is an instance attribute, not a static attribute, so you want to use mybutton. foreground cannot be used. If you want to use basic attributes at the top of a property, no error will occur.

If you didn't guess about the above error, let me tell you a joke.

 

 

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.