UWP development: use custom actions to simplify and reuse code. uwpaction

Source: Internet
Author: User

UWP development: use custom actions to simplify and reuse code. uwpaction

I believe that every App developer will use some code repeatedly during the development process, such as copying text, making phone calls, sending text messages, sending emails, and adding comments to apps. Copying these code segments between projects is not a good method, so you may put the code in a Class similar to Utility or a Library before calling it. This article also helps you do the same thing, but it is done through Action. The two methods have the same purpose. The difference is that, despite the code segment encapsulation, the former still needs to write code (usually in ViewModel) for calling, while the latter, you only need to add several lines of code on the XAML. In comparison, the latter is more convenient.

The Action here comes from the concept in the Behaviors SDK and is actually a class that implements the IAction interface. I will not introduce the basic knowledge about Behaviors SDK in this article. If you do not know enough about it, you can search for related articles in the garden and learn from them (in the final reference article of this article, I have already listed a good article ).

Essentially, actions have the same purpose as Behavior, and they are a piece of code that can be reused. In the IAction interface it implements, an Execute method is defined. This method will be executed when the conditions are met, the condition may be that the control event is triggered, or the property is changed. In the Execute method, we can call methods that can complete the tasks we want.

To meet the preceding requirements, we first create a UWP project and add the Behavior SDK reference for it (this project is mainly for the Action created after the test ).

Create a new class named CommonTaskAction. This class implements the IAction interface and we make it inherit from the DependencyObject class, so that we can define the dependency attribute for it, to assign values to them through Binding in XAML. As follows:

public class CommonTaskAction : DependencyObject, IAction{
        public object Execute(object sender, object parameter)
        {
}}

Then, define an enumeration to express common task types as follows:

Public enum CommonTaskType {// <summary> /// copy the text /// </summary> CopyText, /// <summary> /// call /// </summary> MakePhoneCall ,}

Next, add several dependency attributes for the CommonTaskAction class: TaskType (Task Type), TextToBeCopied (text to be copied), PhoneNO (phone number), and PhoneDisplayName (display name when calling ), as follows:

        public static readonly DependencyProperty PhoneDisplayNameProperty =            DependencyProperty.Register("PhoneDisplayName", typeof(string), typeof(CommonTaskAction), new PropertyMetadata(string.Empty));                public static readonly DependencyProperty PhoneNOProperty =            DependencyProperty.Register("PhoneNO", typeof(string), typeof(CommonTaskAction), new PropertyMetadata(string.Empty));                public static readonly DependencyProperty TaskTypeProperty =            DependencyProperty.Register("TaskType", typeof(CommonTaskType), typeof(CommonTaskAction), new PropertyMetadata(0));                public static readonly DependencyProperty TextToBeCopiedProperty =            DependencyProperty.Register("TextToBeCopied", typeof(string), typeof(CommonTaskAction), new PropertyMetadata(string.Empty));        public string PhoneDisplayName        {            get { return (string)GetValue(PhoneDisplayNameProperty); }            set { SetValue(PhoneDisplayNameProperty, value); }        }        public string PhoneNO        {            get { return (string)GetValue(PhoneNOProperty); }            set { SetValue(PhoneNOProperty, value); }        }        public CommonTaskType TaskType        {            get { return (CommonTaskType)GetValue(TaskTypeProperty); }            set { SetValue(TaskTypeProperty, value); }        }        public string TextToBeCopied        {            get { return (string)GetValue(TextToBeCopiedProperty); }            set { SetValue(TextToBeCopiedProperty, value); }        }

In this case, complete the main logic in the Execute method and add the following code:

Public object Execute (object sender, object parameter) {switch (TaskType) {case CommonTaskType. CopyText: if (! String. isNullOrWhiteSpace (TextToBeCopied) {// copy the text DataPackage dataPackage = new DataPackage {RequestedOperation = DataPackageOperation. copy,}; dataPackage. setText (TextToBeCopied); Clipboard. setContent (dataPackage);} break; case CommonTaskType. makePhoneCall: if (! String. IsNullOrWhiteSpace (PhoneNO) {// call Windows. ApplicationModel. CILS. PhoneCallManager. ShowPhoneCallUI (PhoneNO, PhoneDisplayName);} break;} return true ;}

In this way, a custom Action is complete. Currently, it only adds the logic of copying text and making calls. You can add other logic as needed.
Next, let's look at how to use it. Add the following code to MainPage. xaml:

<Page ...      xmlns:Core="using:Microsoft.Xaml.Interactions.Core"      xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"      xmlns:MyAction="using:CustomActionTest.Actions"

 

<Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid Margin = "12"> <Grid. rowDefinitions> <RowDefinition Height = "Auto"/> <RowDefinition Height = "Auto"/> </Grid. rowDefinitions> <TextBlock Style = "{ThemeResource TitleTextBlockStyle}" Text = "CommonTaskAction test"/> <StackPanel Grid. row = "1" Orientation = "Horizontal"> <TextBox x: Name = "txtName" Width = "400" Text = "here is the test Text"/> <Button C Ontent = "copy"> <Interactivity: Interaction. behaviors> <Core: EventTriggerBehavior EventName = "Tapped"> <MyAction: CommonTaskAction TaskType = "CopyText" TextToBeCopied = "{Binding Text, ElementName = txtName}"/> </Core: eventTriggerBehavior> </Interactivity: Interaction. behaviors> </Button> </StackPanel> <! -- Another MakePhoneCall is not tested here. You can test it by yourself. Usage: --> <! -- <MyAction: CommonTaskAction TaskType = "MakePhoneCall" PhoneNO = "13800 XXXXXX" PhoneDisplayName = "contact name"/> --> </Grid>

Note that the TaskType and value expression are used to copy the text. TextToBeCopied gets the value of the text box through binding. Therefore, this Action can complete the specified task.

After understanding the ideas in this article, you can now transform it into a suitable CommonTaskAction.

If you have better suggestions or comments, please leave a message to communicate with each other.

Source code download

 

References:

Windows general application development notes-Behavior SDK Overview

Behaviors SDK

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.