WPF Resource and wpfresource Resource

Source: Internet
Author: User

WPF Resource and wpfresource Resource

WPF not only supports traditional program-level resources, but also introduces unique object-level resources. Each interface element can carry its own resources and be shared by its own child-level elements. For example, templates, program styles, and themes are often stored in object Resources. In this way, the data in the WPF program is divided into four levels of storage: the data in the database is equivalent to storing in the warehouse, and the data in the resource file is equivalent to putting in the suitcase, the data in the WPF object resource is stored in the carrying backpack, and the data in the variable is stored in the hand.


1. Define and search for WPF object Resources


Each WPF interface element has a property named Resource, which inherits to the FrameworkElement class and its type isResourceDictionary. ResourceDictionary canStore resources as key-value pairsTo use a resource, use a key-value pair to obtain the resource object. When saving a resource, ResourceDictionary regards the resource Object as the Object type. before using the resource, type conversion is required for the resource Object. The XAML compiler can automatically identify the resource type based on the Attribute, if the type is incorrect, an exception will be thrown. However, after retrieving the resource object in C #, we can only convert the type by ourselves. ResourceDictionary can store any type of objects. When adding resources to resources in the XAML code, you need to introduce the correct namespace to The XAML code. Let's look at an example:

<Window x: Class = "WpfApplication10.wnd101" 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 =" MainWindow "Height =" 120 "Width =" 525 "> <Window. resources> <ResourceDictionary> <sys: String x: Key = "_ str"> String </sys: String> <sys: Double x: key = "_ db"> 89.7898 </sys: Double> </ResourceDicti Onary> </Window. Resources> <StackPanel> <! In -- C #, you can use FindResource to find object Resources --> <TextBlock x: name = "_ txtBlock" FontSize = "16" Text = "{StaticResource ResourceKey = _ str}" Height = "28"/> </StackPanel> </Window>

First, we introduce the System namespace Into The XAML code and map it to the sys namespace. Then we add two Resource entries in Windows. Resource, one of which is string type and the other is double type. Finally, we use textBlock to consume this resource. The program running effect is as follows:



When searching for resources, first look for the Resource attributes of the control. If this Resource program does not exist, it searches for the Resource at the upper level along the logic tree. If the Resource does not exist in the top container, the program will find the Application. resource (that is, the program's top-level resources ). If no exception is found, an exception is thrown.
This is like every interface element has its own backpack, which may contain a variety of resources. You can find it when using it, if not, you can view the backpack of the previous control until you find the resource or report that the resource does not exist.


You may wonder if it is better to put resources in a separate folder like CSS or JS to facilitate distribution during full-set reference and re-use? Of course, WPF resources can do this. ResourceDictionary has an attribute named "Source". You only need to assign the file path containing the resource definition to this attribute! For exampleSkinPut it in a resource form in a XAML file. When using it, you only need to add the corresponding XAML file to the project and use the Source attribute for reference. Your program will immediately become glamorous.

<Window. Resources> <! -- One-click skin replacement --> <ResourceDictionary Source = "ShinyRed. xaml"> </ResourceDictionary> </Window. Resources>


2. "dynamic" and "static" Resources


After resources are stored in the resource dictionary, we can use these resources in two ways-static and dynamic. Static resource usageStackResourceIt refers to the one-time use of resources when the program loads memory, and will not be accessed later. Dynamic Resources (DynamicResource) Usage means that resources are still accessed while the program is running. Obviously, if you are sure that some resources are used only once during program initialization and will not change after initialization, StaticResource should be used, and resources may be changed during the program running and should be used in the form of DynamicResource. Take the program topic as an example. If the program skin remains unchanged during running, you can use resources in the Static form. If you are allowed to change the skin or color scheme while running the program, you must use DynamicResource to use the resource.


In the following example, I placed two TextBlock Resources in the Windows resource dictionary and used them in StaticResource and DynamicResource modes:

<Window x: Class = "WpfApplication10.wnd102" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "wnd102" Height = "120" Width = "300"> <Window. resources> <ResourceDictionary> <TextBlock x: Key = "_ txt1" Text = ""> </TextBlock> <TextBlock x: key = "_ txt2" Text = ""> </TextBlock> </ResourceDictionary> </Window. resources> <StackPanel> <Button x: Name = "_ btn1" Content = "{StaticResource _ txt1}" Height = "28"> </Button> <! -- Can be updated only when dynamic resources are running --> <Button x: name = "_ btn2" Content = "{DynamicResource _ txt2}" Height = "28"> </Button> <Button x: name = "_ btn3" Content = "Update" Height = "28" Click = "_ btn3_Click"> </Button> </StackPanel> </Window>

The button is used to change the two resources in the resource dictionary when the program is running:

Private void _ btn3_Click (object sender, RoutedEventArgs e) {this. resources ["_ txt1"] = new TextBlock {Text = "updated successfully"}; this. resources ["_ txt2"] = new TextBlock {Text = "updated successfully "};}


3. Add binary resources to the Assembly


. Dll file ). A Resource file exists in binary data in the target file to form a Resource Section of the target file. Data is extracted when used.


To avoid mixing the resources in the resource dictionary with the embedded Resources in the application, we call the resources in the resource dictionary as"WPF Resources"Or" Object resource ", called" assembly resource "or"Binary Resource". Note that the resources written in the <Application. Resource>... </Application. Resource> label in WPF are still WPF resources rather than binary resources.
Next let's take a look at how to add binary resources to the WPF program and use them.


Resources. resx file content is also organized as a "key-value" pair. After compilation, Resources. resx will formResource class in Properties namespaceYou can use the methods or attributes of this class to obtain resources. To enable the XAML compiler to access this class, you must change the access level of Resources. resx from Internal to public. Using the resource file editor, you can add two entries to the resource file string and access them in The XAML code and C # Code respectively.
To use Resources. resx In The XAML code, you need to map the Properties name of the program to the XAML namespace, and then use the x: Static tag extension to access the resource.

<Window x: Class = "WpfApplication10.wnd103" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns: prop = "clr-namespace: wpfApplication10.Properties "FontSize =" 16 "Title =" wnd103 "Height =" 130 "Width =" 340 "> <StackPanel> <! Properties can be used in -- C. resources. access --> <TextBlock x: Name = "_ txtBlock1" Text = "{x: Static prop: Resources. password} "> </TextBlock> <TextBlock x: Name =" _ txtBlock2 "Text =" {x: Static prop: Resources. userName} "> </TextBlock> </StackPanel> </Window>

To compile an external file into a binary Resource, you must set the value of the Build Action attribute of the file to Resource in the Properties window. Not all files are automatically set to Resource. Compared to file files, MP3 files are not. Generally, if the value of Build Action is set to Resource, the Copy to Output Directory attribute is set to Do Not Copy. If you Do Not want to use an external file as a resource, you can set the Build Action attribute to None, set Copy to Output Directory to Copy Always. In addition, there is a confusing value Embeded Resource in the drop-down list of the Build Action attribute. Do not select this value.


4. Use the pack uri path to Access Binary Resources


WPF has its own method for accessing binary resources, which is called the pack uri path. Sometimes, rote memorization can help readers learn quickly and help them to be lazy. For example, you only need to remember the format of the pack uri path of WPF:

Pack: // application, [/Assembly name;] [Optional version number;] [Folder name/] [file name]

In fact, pack: // applicationi, can be omitted, assembly name and version number are often used with the omitted value, so the only thing left is this:

[Folder name/] [file name]


Let's take a look at the example:



<Window x:Class="WpfApplication10.wnd104"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="wnd104" Height="200" Width="300">    <Grid>        <Image x:Name="_image" Source="Resources/Images/Aodi.jpg" Stretch="Fill"></Image>    </Grid></Window>

You can also use C # To access:

_image.Source = new BitmapImage(new Uri(@"Resources/Images/Aodi.jpg", UriKind.Relative));

Reference: Go to WPF

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.