WPF Language Resources

Source: Internet
Author: User
Tags mscorlib pack parent directory relative xmlns

We refer to useful things as resources. "The horses do not move, fodder first"-----procedures of the various data is the algorithm of raw materials and fodder. There are many places where data can be stored in a program, which can be placed in a database and stored in variables. Between database storage and variable storage, we can also store data in files outside the program body. External files are separated from the program body, which can be lost or corrupted, and the compiler allows us to compile external files into the program body, known as an integral part of the program body. This is a traditional program resource (also known as a binary resource).

WPF not only supports program-level legacy resources, but also introduces unique object-level resources, each of which can carry its own resources and be shared by its own child elements. For example, in the later chapters we will talk about templates, program styles, and topics that are often placed in object resources. In this way, the data in the WPF program is divided into 4 levels of storage: the data in the database is stored in the warehouse, the data in the resource file is equivalent to the suitcase, and the data inside the WPF object resource is stored in the carrying backpack, and the data in the variable is the equivalent of holding it in the hand.

1.1 Definition and lookup of WPF object resources

Each WPF interface element has a property named resource, which inherits to the FrameworkElement class, which is of type ResourceDictionary. ResourceDictionary can store resources in the form of key-value pairs, which are used in the form of key-value pairs to obtain resource objects when a resource is to be used. When you save a resource, the ResourceDictionary resource object is an object type, so when you use the resource to type-convert the resource object, the XAML compiler is able to automatically identify the resource type based on attribute and throws an exception if the type is not correct, but in C # After retrieving the resource object, the type conversion thing can only be done by ourselves.

ResourceDictionary can store any type of object. When adding resources to resource in XAML code, you need to introduce the correct namespaces into your XAML code, let's look at an example:

<window x:class= "wpfapplication1.window31"
        xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "
        xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "
        xmlns:sys=" Clr-namespace:system; Assembly=mscorlib "
        title=" Window31 "fontsize=" "sizetocontent=" Height ">
    <Window.Resources>
        <ResourceDictionary>
            <sys:string x:key= "str" > Sinking boat side thousand sails, the disease tree before the million wood spring. </sys:String>
            <sys:double x:key= "db" >3.1415926</sys:Double>
        </resourcedictionary >
    </Window.Resources>
    <StackPanel>
        <textblock text= "{StaticResource resourcekey= STR} "></TextBlock>
        <!--<textblock text=" {StaticResource resourcekey=db} "></textblock >-->
    </StackPanel>
</Window>

First we introduce the System namespace into the XAML code and map it to the Sys namespace, and then add two resource entries in the Windows.resource, one for string and one for type double. Finally we use two TextBlock to consume these two resources (the commented out code throws an exception because the data type does not match). The program operation effect is as follows:


Because the collection class and label extensions can be abbreviated in XAML code, the more common writing format for the above code is:

<window x:class= "wpfapplication1.window31"
        xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "
        xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "
        xmlns:sys=" Clr-namespace:system; Assembly=mscorlib "
        title=" Window31 "fontsize=" "sizetocontent=" Height ">
    <Window.Resources>
            <sys:string x:key= "str" > Sinking boat side thousand sails, the disease tree before the million wood spring. </sys:String>
            <sys:double x:key= "db" >3.1415926</sys:Double>
    </Window.Resources>
    <StackPanel>
        <textblock text= "{StaticResource str}" ></TextBlock>
        <!--< TextBlock text= "{StaticResource resourcekey=db}" ></TextBlock>-->
    </StackPanel>
</ Window>
When looking for a resource, look for the control's own Resource property, and if not, the program will find the Application.resource (that is, the top-level resource for the program) if none of the top-level containers are looking up in the logical tree. If you haven't found it, you can only throw an exception.

This is like each interface element has its own backpack, which may contain a variety of resources, the use of the time to open the search, if not found can also go to look at a layer of control backpack, until the resource is found or the report does not have this resource.

If you want to use the resources defined in the XAML code inside the C # code, the approximate format is:

        private void Window_Loaded (object sender, RoutedEventArgs e)
        {
            String text = (string) this. FindResource ("str");
            Txt0. Text = text;
        }

Or if you explicitly know that resources are in that resource dictionary, you can retrieve resources like this:

        private void Window_Loaded (object sender, RoutedEventArgs e)
        {
            String text = (string) this. resources["str"];
            Txt0. Text = text;
        }

You might think that if you put a resource like CSS or JS in a separate folder, when using a set of reference, reuse, easy to distribute is not better. WPF resources can of course do this; ResourceDictionary has a property named source, so long as the file path containing the resource definition is assigned to this property, it's all done. For example, Http://wpf.codeplex.com contains a number of official/semi-formal WPF resources, including the WPF toolkit and a very beautiful set of program skins, which are placed in a XAML file in the form of resources. Just add the appropriate XAML file to the project and use the Source property to refer to it, and your program will immediately become a glamorous person.

<resourcedictionary source= "Shinyred.xaml" >
            
</ResourceDictionary>
The operation effect is as follows:

1.2 "dynamic" and "static" resources

When resources are stored in resource dictionaries, there are two ways we can use these resources-----static and dynamic ways. Static and dynamic Two words are our old friends, when this word appears at the same time static refers to the non-execution state of the program and dynamic refers to the running state of the program. Static and dynamic also mean the use of resources. Static resources use Stackresource refers to the one-time use of resources when the program loads into memory, and then does not go to access the resource; dynamic resource (DynamicResource) use refers to the resource that is still being accessed while the program is running. Obviously if you make sure that some resources are used only once and then no longer change after the program is initialized, you should use StaticResource, and the process may change resources to be used in DynamicResource form. Take the subject of the program for example, if the skin of the program is always the same in the process of operation, the use of resources in static form can be. If you allow users to change skins or color schemes while the program is running, you must use DynamicResource to consume resources.

Take a look at the example below, where I put two TextBlock type resources in the Windows resource dictionary, and use them in both StaticResource and DynamicResource ways:

<window x:class= "Wpfapplication1.window32"
        xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "
        xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "
        title=" Window32 "fontsize=" 16 " windowstyle= "ToolWindow" >
    <Window.Resources>
        <ResourceDictionary>
            <textblock x: key= "Res1" > Sea-born Moon </TextBlock>
            <textblock x:key= "Res2" > Sea Life Moon </TextBlock>
        </ resourcedictionary>
    </Window.Resources>
    <StackPanel>
        <button content= "{ StaticResource res1} "margin=" 5 "></Button>
        <button content=" {DynamicResource res2} "margin=" 5 "> </Button>
        <button content= "Update" margin= "5" click= "Button_Click" ></Button>
    </ Stackpanel>
</Window>

The third button on the interface is responsible for changing the two resources in the resource dictionary during the program's run:

        private void Button_Click (object sender, RoutedEventArgs e)
        {this
            . resources["res1"] = new TextBlock () {text= "Tianya total at this time"};
            This. resources["Res2"] = new TextBlock () {Text = "Tianya total at this time"};
        }
In fact, because the first button is using the resource statically, it is not known even though the resource has been updated. Run the program, click the Third button, the effect is as follows:

1.3 Adding a binary resource to an assembly

For the concept of resources, it is confusing for WPF beginners because window applications are already able to carry resources before WPF appears. The principle of Windows application resources is similar to WinZip or WinRAR compression packages, in fact, some applications must use resources and applications themselves packaged together so that resources are not accidentally lost (the side effect is that the application volume will become larger). Common application resources include icons, pictures, text, audio, video, etc., and compilers or resource compilers of various programming languages have the ability to compile these files into the target file (the final. exe file or. dll file). The resource file exists as binary data in the target file, forming the resource segment (Resource section) of the target file, and the data is extracted when it is used.

In order not to confuse resources in the resource dictionary with resources embedded in the application, we explicitly address resources in the resource dictionary as "WPF resources" or "Object Resources", which are called "Assembly resources" or "binary resources" in the application's embedded resources. In particular, the resources written in WPF in the <Application.Resource>...</Application.Resource> tag are still WPF resources, not binary resources.

Let's take a look at how to add binary resources to WPF programs and use them.

If the resource to be added is a string rather than a file, we can use the Resources.resx resource file under the application namespace. Open the resource file by expanding the Properties folder in Project Manager and double-clicking the following Resources.resx resource file. As shown in the following illustration:


The organization of RESOURCES.RESX file contents is also a "key-value" pair, and after compiling, Resources.resx will form the resource class in the Properties namespace, which can be used to obtain resources using the method or property of this class. In order for the XAML compiler to access this class, be sure to change the Resources.resx access level from internal to public. Using the resource file editor, you can add two entries to the string in the resource file, and then access them in XAML code and in C # code, respectively.

Using resources in Resources.resx in XAML code, you need to map the program's properties name to a XAML namespace, and then use the x:static label extension to access the resource.

<window x:class= "wpfapplication1.window33" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prop= "Clr-namespace:wpfapplication1.properties" Title= "Window33" height= "width=" > <Grid> <Grid.RowDefinitions> &L T RowDefinition height= "/> <rowdefinition height=" 4 "/> <rowdefinition height=" 23 "/ > </Grid.RowDefinitions> <Grid.ColumnDefinitions> <columndefinition width= "A Uto "/> <columndefinition width=" 4 "/> <columndefinition width=" * "/> </ grid.columndefinitions> <textblock x:name= "txtname" text= "{x:static prop:Resources.userName}" ></textbl ock> <textblock x:name= "Txtpass" grid.row= "2" ></TextBlock> <textbox borderbrush= "Black" Grid.column= "2" ></textbox> <textbox borderbrush= "Black" grid.row= "2" grid.column= "2" ></TextBox> </Grid>
 </Window>
The resources for accessing Resources.resx in C # are used with the general indistinguishable:

        Public Window33 ()
        {
            InitializeComponent ();
            This.txtPass.Text = Properties.Resources.pass;
        }
The operation effect is as follows:

The biggest advantage of using RESOURCES.RESX is that it facilitates internationalization and localization of programs. If you want to change the interface to English, simply change the value in the resource to English, as shown in the following illustration, because the resource is used in the program to access resources using the name of the resource, so the code does not need to be changed:

If the resource you want to add is not a string, it is an icon, picture, audio, or video screen. The method does not use Resources.resx, and WPF does not support this. When WPF uses external files as a resource, it simply needs to be put into the project. The method is to right-click on the project name in the project manager, select New-->newfolder in the popup menu, create a few layers of folders as needed to store the resources, then right-click on the appropriate folder and select Add--->existing item in the popup menu ... When you select a file in the file dialog box and click the Add button, the file is added to the project as a resource.

If you add a MP3 file and a picture file inside the program, the volume of the resulting file expands several megabytes. The following figure:



It is important to note that if you want to compile the external file into a binary resource, you must set the file's Build Action property value to resource in the Properties window. Not every file is automatically set to resource, such as picture files, MP3 files will not, in general, if the value of the build action is set to resource, then the copy to Output directory property is set to does not Copy; If you do not want to use the external file as a resource, you can set the Build Action property to None and copy to Output directory as copy always. In addition, the drop-down list of the Build Action property has a confusing value embeded Resource, do not select this value.


1.4 Using the Pack URI path to access binary resources

WPF access to binary resources has its own set of methods, called the Pack URI path. Sometimes rote learning allows the reader to learn quickly and help the author to steal some slack. For example, the pack URI path for WPF, you just have to remember this format:

Pack://application,,, [/assembly name;] [optional version number;] [Folder name/] [File name]

In fact Pack://applicationi,,, can be omitted, the assembly name and version number often use the ellipsis, so the only thing left is this:

[Folder name/] [File name]
In the previous example, we added a picture named 20090102191236877.gif to the resource, its path in the project is Resource/image/20090102191236877.gif, intact, Using this path, you can access the image. We fill a <Image/> element with this image and use the <image/> element as the background of the form.

<window x:class= "wpfapplication1.window34"
        xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "
        xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "
        title=" Window34 ">
    <grid >
        <image source= "resource/image/20090102191236877.gif" x:name= "img0" stretch= "Fill" ></Image>
    </Grid>
</Window>
Or

<window x:class= "wpfapplication1.window34"
        xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "
        xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "
        title=" Window34 ">
    <grid >
        <image source= "pack://application:,,,/resource/image/20090102191236877.gif" x:name= "img0" Stretch= " Fill ></Image>
    </Grid>
</Window>
The equivalent C # code is as follows:

        Public Window34 ()
        {
            InitializeComponent ();
            Uri Imageuri = new Uri (@ "Resource/image/20090102191236877.gif", urikind.relative);
            This.img0.Source = new BitmapImage (Imageuri);
        }
Or

        Public Window34 ()
        {
            InitializeComponent ();
            Uri Imageuri = new Uri (@ "pack://application:,,,/resource/image/20090102191236877.gif", urikind.absolute);
            This.img0.Source = new BitmapImage (Imageuri);
        }

The results of the operation are as follows:

There are a few things to note when using the Pack URI path:

The Pack URI uses a right-to-left forward slash (/) to represent the path. Using a slight write means a relative path, urikind in C # code must be relative and the/can be omitted to represent the root directory. Using full notation is an absolute path, and UriKind in C # code must be absolute and represent the root directory/cannot be omitted. Using a relative path can be navigated with a DOS-like syntax, such as./representing sibling directories,. /represents the parent directory.









Reprint Please specify source: http://blog.csdn.net/fwj380891124






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.