Create UserControl in wpf

Source: Internet
Author: User

In the previous article, we mentioned that UserControl is mainly a combination of existing controls. Combination is a good combination. I drag a few controls to put them in the page. For example, if I get a TextBox and a button to the side of the page, the combination name is UserControl, the problem is that this UserControl is useless. For example, in the WPF form, I want to assign values to the TextBox in UserControl or obtain its value. How can I get it? I want to click the Button in UserControl to trigger an event in the background code file (MVVM mode not mentioned) of the WPF form in which UserControl is located. How can I trigger this event? These two problems are the key issues for creating UserControl.

First question: Get or set attributes.

Create a wpf user control project and add a Button and TextBox in UserControl1.xaml. The user control inherits from the UserControl class by default. You can also modify the inherited class. If it is changed to another class, UserControl will have the corresponding methods and attributes of this class. Do not modify it here to keep its default inheritance.

Now the main task is to get or set the TextBox Value in the form after the user control is placed in the WPF form.

The key step is to addDependency attribute.

For example, I want to add a Text attribute to this user control, that is, when I put this user control in the WPF window, I want to get or set its Text attribute.

The code for adding this Text dependency attribute is as follows:

In this way, the user control

public static readonly DependencyProperty TextProperty =           DependencyProperty.Register("Text", typeof(string),           typeof(UserControl1),           new PropertyMetadata("TextBox", new PropertyChangedCallback(OnTextChanged)));        public string Text        {            get { return (string)GetValue(TextProperty); }            set { SetValue(TextProperty, value); }        }        static void OnTextChanged(object sender, DependencyPropertyChangedEventArgs args)        {            UserControl1 source = (UserControl1)sender;            source.tb.Text = (string)args.NewValue;        }

Added an attribute named Text. If you are doing something in this area or learning something in this area, you can see this article through search. It is estimated that someone will directly copy the above Code to see the implementation, so I am very happy. This is fast, but it is not a fish. The main sentence code here is

public static readonly DependencyProperty TextProperty =           DependencyProperty.Register("Text", typeof(string),           typeof(UserControl1),           new PropertyMetadata("TextBox", new PropertyChangedCallback(OnTextChanged)));

Then the DependencyProperty. Register method is used.

The first parameter is the name of the property you want to add to the user control, that is, the string you enter in the first parameter. In the future, your user control will add this string as the name attribute.

The second parameter indicates the data type corresponding to this attribute.

The third parameter indicates the type of the property owner.

The callback event triggered when the fourth parameter property is changed.

After understanding this method and its parameters, it is easy to add attributes to the user control.

The second big problem below,Event Circulation.

For example, we want to expose this user control to a form MyButtonClick event. The Code is as follows:

public static readonly RoutedEvent MyButtonClickEvent =            EventManager.RegisterRoutedEvent("MyButtonClick", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<object>), typeof(UserControl1));        public event RoutedPropertyChangedEventHandler<object> MyButtonClick        {            add            {                this.AddHandler(MyButtonClickEvent, value);            }            remove            {                this.RemoveHandler(MyButtonClickEvent, value);            }        }        public void OnMyButtonClick(object oldValue, object newValue)        {            RoutedPropertyChangedEventArgs<object> arg =                new RoutedPropertyChangedEventArgs<object>(oldValue, newValue, MyButtonClickEvent);                       this.RaiseEvent(arg);        }

In this way, through the two pieces of code, your user control will get a Text attribute and a MyButtonClick method.

Note that in the above two sections of code, especially the code for event registration in the second section, when your user control inherits different base classes, the parameters that may be used when registering an event are different from the event type. For example, an example on msdn is inherited from the Button, where the event types and parameters are different:

public class MyButtonSimple: Button{    // Create a custom routed event by first registering a RoutedEventID    // This event uses the bubbling routing strategy    public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(        "Tap", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButtonSimple));    // Provide CLR accessors for the event    public event RoutedEventHandler Tap    {            add { AddHandler(TapEvent, value); }             remove { RemoveHandler(TapEvent, value); }    }    // This method raises the Tap event    void RaiseTapEvent()    {            RoutedEventArgs newEventArgs = new RoutedEventArgs(MyButtonSimple.TapEvent);            RaiseEvent(newEventArgs);    }    // For demonstration purposes we raise the event when the MyButtonSimple is clicked    protected override void OnClick()    {        RaiseTapEvent();    }}

You can create a project to reference this class library. Try it.

Leave a message if you have any questions.

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.