Continue to the same topic: Resources in WPF. This time I will try to analyze the resources in WPF from another perspective: Resource compilation behavior, and how to select appropriate types based on application needs.
First, create a default WPF project and add an ICON resource to the project. After adding a resource, we can select the resource type, as shown in:
You can see the various types supported by resources in the drop-down list. The main supported compilation behaviors are Resource and Content. If you select Resource, open the C # project file (*. csproj file) in text mode. The following content is found:
<ItemGroup>
<Resource Include = "WTL2007.ico"/>
</ItemGroup>
If you select "Content", the displayed resource items should be:
<ItemGroup>
<Content Include = "WTL2007.ico"/>
</ItemGroup>
So what is the difference between the two? Let's first look at the Resource type. If a file is identified as a Resource in the project text, it is embedded in the Assembly where the application is located. If Localizable metadata is set, the corresponding Resource file is located in satellite Assembly.
After the project is compiled, all the specified resource files in the project create a. resources file together. For localized applications, the corresponding satellite Assembly will be loaded.
If the file is identified as Content and CopyToOutputDirectory is set to Always or PerserveNewest. This file is copied to the compilation output directory together with the application Assembly.
<Content Include = "WTL2007.ico">
<CopyToOutputDirectory> Always </CopyToOutputDirectory>
</Content>
During compilation, all files marked as Content are created with a file ing relationship. During runtime, the WPF loading mechanism loads resources according to the specified Uri.
No matter whether the referenced type is Resource or Content, in the code, we can access these resources through a simple Uri:
<Object Property = "WTL2007.ico"/>
Below are some good suggestions to help us select the compilation Action of resources. For the following requirements, select Resource:
1. Files are local files.
2. After the application is deployed, you do not want the file to be modified.
3. If you do not want to deploy or manage files separately, do not worry about the resource location when moving applications.
For the following resource file requirements, we should select Content:
1. files are not local files
2. You want to replace the file after deployment.
3. You want the file to be downloaded and updated, and so on (note that it cannot be included in the application Assembly ).
4. Some files cannot be set to Resource type; otherwise, WPF cannot recognize them.