Blog Park Client UAP Development Essay--an arm of custom controls

Source: Internet
Author: User

Objective

The last time we talked about the app's Genie: the custom control. This time, let's go on to this topic and talk about the two right-hand helpers for custom controls:

    • Selector-Templateselector
    • Converter –converter

These two things can help customize the control to be used more easily and conveniently, so it must be mastered.

Value Converter Converter

This is probably not a stranger, because on MSDN, when introduced to the data binding, always go with the introduction of the conversion, such as this page:

http://msdn.microsoft.com/library/windows/apps/xaml/hh464965.aspx/

The last Stringformatter is.

In the blog Park UAP, we used several converter, each converter is actually a CS class, derived from the IValueConverter interface. They are all placed in the Controlhelper directory of the Cnblogs.shared project. Let's use two examples to illustrate this.

Conversion of Bool/visibility

Let's look at this code:

 Public classbooltovisibilityconverter:ivalueconverter{ Public ObjectConvert (ObjectValue, Type TargetType,ObjectParameterstringlanguage) {            return(BOOL) value?Visibility.Visible:Visibility.Collapsed; }         Public ObjectConvertback (ObjectValue, Type TargetType,ObjectParameterstringlanguage) {            Throw Newnotimplementedexception (); }}

The function is straightforward, which is to convert the bool value to an visibility enumeration value, and then bind to an element of a control, for example, in XAML:

<TargetType= "Local:favoriteauthorcontrol">        <  Property= "Template">            <Setter.value  >
...
 <  textblock  Span style= "color: #ff0000;" >grid.column  = "0"   Text  = ""   FontFamily    Foreground  =" Red "  Visibility  = " {binding converter={ StaticResource booltovisiblityconverter}, path=hasnew}   " />  
...            </ Setter.value >        </ Setter > </ Style >

The above XAML is a style description for a custom control, and the control itself is the "main blogger" Control on the "Favorites" page, which is designed to: when the Hasnew field value is true, a small red star appears to the left of the blogger's avatar, indicating that the blogger has a new blog published, If you pay attention to the blogger, you can click to see his new blog. When Hasnew is false, do not show the small stars, you do not need to go in to see a lap, found no new blog and then disappointed to leave.

Some people may say: I in FavoriteAuthorControl.cs code, directly take Hasnew value, see whether it is true or false, and then directly with code write visibility = visiable or collapsed can.

This is certainly OK, but there are a few inconvenient places:

1) You need to write code

2) The person reading your program, if not read your code, do not know this logic

3) You need to name the TextBlock (x:name= ...) Then use Getchildtemplate ("...") in code to get the control, and then specify its visibility value.

4) In other controls, you still have to write code to do something like that.

The benefits of using our recommended approach are obvious:

1) Bind in XAML, no code

2) This converter can be reused

3) No more definition, one-time solution in the binding phase (this is also a benefit of WPF), performance is not considered

4) Excellent readability

Bool/string Converters

To give an example to solidify, on code:

Class nightmodelabelconverter:ivalueconverter{Public        object Convert (object value, Type targetType, Object parameter, String language)        {            bool BValue = (bool) value;            if (BValue)            {                return "day mode";            }            else            {                return "night Mode";            }        }        public object Convertback (object value, Type targetType, object parameter, string culture)        {            throw new notimple Mentedexception ();        }}

This is used in XAML:

<x:nameConverternightmodelabelconverter}, Path =settings.nightmode "/>

This binding process first checks the value of Nightmode in setting and, if true, displays "Day mode" below the button, or "Night mode" if False.

Template selector Templateselector

Template selector Very few people use, because the introduction of its very few documents, so far we have not found, but also a chance to know that there is such a thing, very useful! Remember how many times we interviewed, we all asked this question: if a piece of news has a picture, another piece of news does not have a picture, how are you going to show the two control? As shown, the top one has a picture (deliberately marked with a red rectangle), the following is no picture.

We get two answers:

1) make a generic control, and then automatically display the image to the right according to the URL with no image

2) Use code to control whether the right image is displayed in the custom space

Of course! All of this can be achieved with this goal. But note that there is a gray vertical line on the left side of the picture.

Today we recommend a more standard generic approach: Templateselector.

First on code:

namespacecnblogs.controlhelper{classNewscontroltemplateselector:datatemplateselector { PublicDataTemplate Dthasimage {Get;Set; }  PublicDataTemplate Dtnoimage {Get;Set; } protected OverrideDataTemplate Selecttemplatecore (Objectitem, DependencyObject container) {CNBlogs.DataHelper.DataModel.News News= Item asCNBlogs.DataHelper.DataModel.News; if(string. IsNullOrEmpty (news. Topicicon)) {returnDtnoimage; }            returnDthasimage; }    }}

In shared project, there is a NewsControlTemplateSelector.cs in the Controlhelper directory. It derives from the Datatemplaterselector parent class, first defining two datatemplate:dthasimage and Dtnoimage, respectively, corresponding to two cases with or without a picture. Then, in the Selecttemplatecore rewrite method, get news instance first, determine whether Topicicon exists, if present, return dthasimage, otherwise return dtnoimage.

In MainPage.xaml, this is done using:

<page.resources>......        <DataTemplatex:key= "Newsnoimagetemplate">            <Local:newstitletextcontrol/>        </DataTemplate>        <DataTemplatex:key= "Newshasimagetemplate">            <Local:newstitletextimagecontrol/>        </DataTemplate>......</page.resources>

First define two template in Page.resource, give two different key value, one is called "Newsnoimagetemplate", the other is called "Newshasimagetemplate", Corresponds to two custom Control:newstitletextcontrol and Newstitletextimagecontrol respectively (in theme\ Generic.xaml, one with only the title text, the other with the title text and the right picture).

Then write this in the ListView of news PivotItem:

<PivotItemMargin= "0"Tag= "News">......                <Listview.itemtemplateselector>                    <Controlhelper:newscontroltemplateselectorDthasimage="{StaticResource Newshasimagetemplate}"Dtnoimage="{StaticResource Newsnoimagetemplate}"/>                </Listview.itemtemplateselector>        </ListView></PivotItem>

Listview.itemtemplateselector is used to define the current news with what template to display. Note the following syntax:

1) Controlhelper:newscontroltemplateselector class name corresponding to the first section of CS code

2) Dthasimage/dtnoimage corresponds to two return values in CS code

3) StaticResource newshasimagetemplate corresponds to the x:key= "Newshasimagetemplate" in page.resources, which corresponds indirectly to a custom control template with a picture.

That is: Control <-> resource File <-> selector. The relationship between the three is easy to confuse, especially the name, especially easy to make mistakes, so that in the end they do not remember what corresponds. The suggestion is that the control does the end, such as Newtitletextcontrol; the key of the resource file is terminated with a template, such as newsnoimagetemplate; the selector starts with DT, such as Dtnoimage. In this case, if there is a picture, selector will return to Dthasimage, which corresponds to the StaticResource newhasimagetemplate in the resources on this page, The Newstitletextimage custom control is used to display the news.

Summary

Well, having mastered the first converter, we don't have to write code in every control, and we can bind it directly in XAML. Having mastered the second selector, we can fully decompose the page logic and granular it to a reasonable degree without having to consider how to display two or more styles with one control.

But note that in the previous "app Elf" essay, mentioned Postcontrol control, sometimes to show the author's Avatar, sometimes to show "I have read" and so on, if you want to make 5 control, and then use Templateselector to choose is wrong. The basic principle is: In a ListView, if there are more than two styles of choice, with Templateselector; on two pages, use the TemplateBinding external configuration to specify whether you want to display an element. For example, authoravatar.visibility = {TemplateBinding Showavatar}, when using it, you can specify visable or collapsed in two pages individually, allowing one control to be used in 5 cases.

In Windows Phone 8.1 and Windows 8.1, there is no difference, so we put these CS in shared project so that we can share it in two projects.

Share the code and change the world!

Windows Phone Store App Link:

http://www.windowsphone.com/zh-cn/store/app/Blog Park-UAP/500F08F0-5BE8-4723-AFF9-A397BEEE52FC

Windows Store App Link:

http://apps.microsoft.com/windows/zh-cn/app/c76b99a0-9abd-4a4e-86f0-b29bfcc51059

GitHub Open Source Link:

Https://github.com/MS-UAP/cnblogs-UAP

MSDN Sample Code:

Https://code.msdn.microsoft.com/CNBlogs-Client-Universal-9c9692d1

Ms-uap

2015/1/5

Blog Park Client UAP Development Essay--an arm of custom controls

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.