"Win 10 App development" Loading this resource in code

Source: Internet
Author: User

Remember the previous time, the old week to everyone, no, little friends introduced how to fill out the. resw file, and use the x:uid tag in XAML to load. And by the way, we analyzed how the runtime parses. resw files.

Originally agreed, the following old week will write an article on how to manually load this resource in the Code blog post, but dragged to today, because the old week before the son is busy to develop their own UWP app, has submitted a version to the store, just submitted an update yesterday.

OK, today we'll talk about the code to load this resource.

Using UID to load resources in XAML is convenient, but it has one drawback-different controls have different properties, sometimes it's not easy to match, and of course, if your resources are targeting a few types of controls, it doesn't matter.

To compensate for the lack of UID loading, we can write the resource load code ourselves. This practice has always been customary in the old weeks. You should remember that year's WinForm application, which is also a (. resx) that can translate and edit resources directly in the designer, and then VS will help us generate a class for managing resources.

In the actual development, the old Monday to not use this trick, is generally their own write resources class, so very flexible, you can freely control, and then let the resource class exposes some properties, and then binding with the UI. The old weeks in WPF did not develop too many language applications, so there was no way to get them.

Similarly, in a UWP app we can still encapsulate it ourselves and then bind it to the UI so that it's easy to manage and can be used for both XAML and non-XAML code. Therefore, it is very meaningful. Sometimes, more toss is also good, love tossing life more wonderful. So, last spring old weekly hours PR, summer study AE, fall study CAD, Winter learn gourd silk. This year to learn SLR camera, Ching Ming Festival bau, Labor Day after the electrical maintenance, please in the gas company work students teach me to install gas stove, July study ocarina, September to see the master to do silk roll painting, October copy Liu Gongquan "occult Tower Monument".

Once a person has something to do, he will not be paranoid.

The following old week shows an example.

The project puts two resource files, one is English resources, the other is Chinese resources.

In the Chinese language resource, enter the following three items.

In the English language resource, enter the following three items.

Once the resources are ready, let's start packing. In fact, in the UWP, there is a very nnd simple way to load resources with the Windows.ApplicationModel.Resources namespace.

Resourceloader class. This class is very useful, call the static Getforcurrentview method to get an instance, and then use the GetString method can be loaded into the string resources.

Note that the Getforcurrentview method has two overloads, one with parameters, and the parameter specifies your. resw file name, without the path and extension, which was introduced in the previous bird's old week, for example, in this case, the resource file is goods.<language tag >.RESW, so the parameter passed is Goods. The other is the Getforcurrentview method without parameters, and if you call this version of the overload, then your. resw file must be named RESOURCES.RESW, as RESOURCES.LANG-ZH-CN.RESW,RESOURCES.LANG-ZH-TW.RESW and so on.

First look at the packaged classes.

     Public classresourcesitems:inotifypropertychanged {Static ReadOnlyResourcesitems minstance =NewResourcesitems ();  Public StaticResourcesitems Current {Get{returnminstance;} }        PrivateResourcesitems () {//load at construction time, populate default valuesLoad (); }         Public EventPropertyChangedEventHandler propertychanged; Private voidOnPropertyChanged (stringpropname) {propertychanged?. Invoke ( This,NewPropertyChangedEventArgs (propname)); }         Public voidLoad () {varLoader = Resourceloader.getforcurrentview ("Goods"); Item1= Loader. GetString ("T1"); ITEM2= Loader. GetString ("T2"); Item3= Loader. GetString ("T3"); }        #regionPropertystring_it1, _it2, _it3;  Public stringItem1 {Get{return_it1;} Set            {                if(Value! =_it1) {_it1=value;                OnPropertyChanged (nameof (Item1)); }            }        }         Public stringItem2 {Get{return_it2;} Set            {                if(_it2! =value) {_it2=value;                OnPropertyChanged (nameof (ITEM2)); }            }        }         Public stringItem3 {Get{return_it3;} Set            {                if(_it3! =value) {_it3=value;                OnPropertyChanged (nameof (ITEM3)); }            }        }        #endregion    }

Here I use Item1, Item2, and Item3 three properties corresponding to the three items in the resource file. Implementing the INotifyPropertyChanged interface is a very epoch-making strategy, so that when the language is changed, the binding on the UI can get the most recent value in real time when the document is reloaded from the resource file.

In 99.99986% of the scenarios, we only need to instantiate the resource class once, so keep it in the application life cycle only one instance, there is no need to create such instances, wasting food chain resources. Therefore, you can privatize the constructor and then expose an instance of the current class with a static, read-only property. That

        Static ReadOnly New Resourcesitems ();          Public Static Get return minstance; } }

This class can expose a method that allows external calls to load resources.

 public  void   Load () { var  loader = Resourceloader.getforcurrentview (
   
     " 
    goods  
    "  
     = loader. GetString ( t1   "            ); ITEM2  = loader. GetString ( t2   "            ); ITEM3  = loader. GetString ( t3   "        ); }
   

Go back to the application page class, such as the MainPage class generated by the project template, and expose the resource management class as a property.

        resourcesitems theres        {            getreturn  resourcesitems.current;}        }

Someone would say, Old week, why are you so superfluous? Because later I'm going to bind with X:bind, but the XAML compiler has a "eight elder brother", and when you use X:bind to indirectly bind to the instance, a compilation error occurs. It is said that the SDK development team has received this issue report in July this year and will be repaired in the future. Anyway, Autumn update 1709,16299 has not been repaired.

That is, if you bind like this, it will go wrong.

<= "{x:bind ResourceItems.Current.Item1}"   />

So, in order to avoid this flaw, you can seal it in the page class, and then we can point the source of the x bind to this property of the page class, so that there is no error.

   <TextBlock>       <Run Text= " {x:bind Theres.item1,mode=oneway}"FontSize= "+"Foreground= "Blue"/>       <Run Text= " {x:bind Theres.item2,mode=oneway}"FontSize= "+"Foreground= "Red"/>       <Run Text= " {x:bind Theres.item3,mode=oneway}"FontSize= "+"Foreground= "Darkblue"/>    </TextBlock>

With this binding, we can modify the language of the application in real time in the code, and then reload the resource class that was just encapsulated.

Here, a method is deliberately encapsulated to change the current language of the application.

        Private void Setlang (string  lang)        {            var context =  Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView ();             var qs = context. qualifiervalues;             // This can also modify the language            of the current application qs["Language"] = lang;        }

ResourceContext is responsible for the application context of the resource settings, where we have two ways to change the language, one is to change the Languages attribute, note that it is a list, that is, you can set a series of language combinations, the default application should be the first in the list (in advance is it with the current The same language as the Win 10 system).

However, I chose to use the second method, which is to obtain a dictionary from the Qualifiervalues attribute, which is the qualifier used to describe the current application resource, Key is the qualifier name, and value is of course the corresponding values. What is a qualifier? For example, the current application language, screen scale, whether high contrast, whether to rotate the screen and so on.

If you're curious about what's inside, you can use the following code to output it.

#if DEBUG            varnew  System.Text.StringBuilder ();             foreach (var in Qs)            {                string ts = $'{item.} Key} = {item. Value}";                STRBD. Appendline (TS);            }            System.Diagnostics.Debug.WriteLine ($"\n\n{strbd}\n\n"); #endif

Then you will see output similar to the following.

Language = ZH-CN
contrast = Standard
Scale = 100
Homeregion = CN
Targetsize =
LayoutDirection = LTR
Theme = Dark
Alternateform =
Dxfeaturelevel =
Configuration =
devicefamily = Desktop
Custom =

See the above output, you understand it. If you don't understand it, go to the wall.

We just need to change the Language value here. So

            var qs = context. qualifiervalues;             // This can also modify the language            of the current application qs["Language"] = lang;

So, someone must have asked the old week, old week you are not amnesia? In the previous article you did not introduce a Windows.Globalization.ApplicationLanguages class, as long as you change the Primarylanguageoverride attribute on it. Yes, that property is really cool, one line of code is done. However, that property is only suitable for non-real-time changes, that is, it may be just the app runtime, or the user can change it when set. Since that property has been modified, it will not take effect immediately, it may take 3 seconds before it refreshes unless you deliberately leave the card for 3 seconds. Otherwise, if you want the switching language to take effect immediately, you will have to change the resource qualifier. Modifier Language is very useful, a change of spirit, real-time refresh.

Well, done, see how it works.

Sample source Code

OK, today's article is written here, another day there are new discoveries, the old weeks will be timely to share. I am now more and more like UWP apps, high performance, able to adapt to high-split screen, as well as the various modes of operation, most importantly, it is safe.

"Win 10 app development" loads this resource in your code

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.