Resources
XAML Resources
https://msdn.microsoft.com/ko-kr/library/ms750613(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/ms750613(v=vs.110).aspx
A resource is an object that can be reused in different places in your application. Examples of resources include brushes and styles. This overview describes how to use resources in XAML. You can also create and access resources by using code, or interchangeably between code and Extensible Application Markup Language (XAML). For more information, see Resources and Code.
Note |
---|
The resource files described in this topic are different than the resource files described in WPF Application Resource, Content, and Data Files and different than the embedded or linked resources described in Managing Application Resources (.NET). |
Using Resources in XAML
The following example defines a SolidColorBrush as a resource on the root element of a page. The example then references the resource and uses it to set properties of several child elements, including an Ellipse, a TextBlock, and a Button.
<Page Name="root" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Page.Resources> <SolidColorBrush x:Key="MyBrush" Color="Gold"/> <Style TargetType="Border" x:Key="PageBackground"> <Setter Property="Background" Value="Blue"/> </Style> <Style TargetType="TextBlock" x:Key="TitleText"> <Setter Property="Background" Value="Blue"/> <Setter Property="DockPanel.Dock" Value="Top"/> <Setter Property="FontSize" Value="18"/> <Setter Property="Foreground" Value="#4E87D4"/> <Setter Property="FontFamily" Value="Trebuchet MS"/> <Setter Property="Margin" Value="0,40,10,10"/> </Style> <Style TargetType="TextBlock" x:Key="Label"> <Setter Property="DockPanel.Dock" Value="Right"/> <Setter Property="FontSize" Value="8"/> <Setter Property="Foreground" Value="{StaticResource MyBrush}"/> <Setter Property="FontFamily" Value="Arial"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="Margin" Value="0,3,10,0"/> </Style> </Page.Resources> <StackPanel> <Border Style="{StaticResource PageBackground}"> <DockPanel> <TextBlock Style="{StaticResource TitleText}">Title</TextBlock> <TextBlock Style="{StaticResource Label}">Label</TextBlock> <TextBlock DockPanel.Dock="Top" HorizontalAlignment="Left" FontSize="36" Foreground="{StaticResource MyBrush}" Text="Text" Margin="20" /> <Button DockPanel.Dock="Top" HorizontalAlignment="Left" Height="30" Background="{StaticResource MyBrush}" Margin="40">Button</Button> <Ellipse DockPanel.Dock="Top" HorizontalAlignment="Left" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="40" /> </DockPanel> </Border> </StackPanel> </Page>
Every framework-level element ( FrameworkElement or FrameworkContentElement) has a Resources property, which is the property that contains the resources (as a ResourceDictionary) that a resource defines. You can define resources on any element. However, resources are most often defined on the root element, which is Page in the example.
Each resource in a resource dictionary must have a unique key. When you define resources in markup, you assign the unique key through the x:Key Directive. Typically, the key is a string; however, you can also set it to other object types by using the appropriate markup extensions. Nonstring keys for resources are used by certain feature areas in WPF, notably for styles, component resources, and data styling.
After you define a resource, you can reference the resource to be used for a property value by using a resource markup extension syntax that specifies the key name, for example:
<Button Background="{StaticResource MyBrush}"/> <Ellipse Fill="{StaticResource MyBrush}"/>
In the preceding example, when the XAML loader processes the value {StaticResource MyBrush} for the Background property on Button, the resource lookup logic first checks the resource dictionary for the Button element. If Button does not have a definition of the resource key MyBrush (it does not; its resource collection is empty), the lookup next checks the parent element of Button, which is Page. Thus, when you define a resource on the Page root element, all the elements in the logical tree of the Page can access it, and you can reuse the same resource for setting the value of any property that accepts the Type that the resource represents. In the previous example, the same MyBrush resource sets two different properties: the Background of a Button, and the Fill of a Rectangle.
Static and Dynamic Resources
A resource can be referenced as either a static resource or a dynamic resource. This is done by using either the StaticResource Markup Extension or the DynamicResource Markup Extension. A markup extension is a feature of XAML whereby you can specify an object reference by having the markup extension process the attribute string and return the object to a XAML loader. For more information about markup extension behavior, seeMarkup Extensions and WPF XAML.
When you use a markup extension, you typically provide one or more parameters in string form that are processed by that particular markup extension, rather than being evaluated in the context of the property being set. The StaticResource Markup Extension processes a key by looking up the value for that key in all available resource dictionaries. This happens during loading, which is the point in time when the loading process needs to assign the property value that takes the static resource reference. The DynamicResource Markup Extension instead processes a key by creating an expression, and that expression remains unevaluated until the application is actually run, at which time the expression is evaluated and provides a value.
When you reference a resource, the following considerations can influence whether you use a static resource reference or a dynamic resource reference:
The overall design of how you create the resources for your application (per page, in the application, in loose XAML, in a resource only assembly).
The application functionality: is updating resources in real time part of your application requirements?
The respective lookup behavior of that resource reference type.
The particular property or resource type, and the native behavior of those types.
Static Resources
Static resource references work best for the following circumstances:
Your application design concentrates most of all of its resources into page or application level resource dictionaries. Static resource references are not reevaluated based on runtime behaviors such as reloading a page, and therefore there can be some performance benefit to avoiding large numbers of dynamic resource references when they are not necessary per your resource and application design.
You are setting the value of a property that is not on a DependencyObject or a Freezable.
You are creating a resource dictionary that will be compiled into a DLL, and packaged as part of the application or shared between applications.
You are creating a theme for a custom control, and are defining resources that are used within the themes. For this case, you typically do not want the dynamic resource reference lookup behavior, you instead want the static resource reference behavior so that the lookup is predictable and self-contained to the theme. With a dynamic resource reference, even a reference within a theme is left unevaluated until runtime, and there is a chance that when the theme is applied, some local element will redefine a key that your theme is trying to reference, and the local element will fall prior to the theme itself in the lookup. If that happens, your theme will not behave in an expected manner.
You are using resources to set large numbers of dependency properties. Dependency properties have effective value caching as enabled by the property system, so if you provide a value for a dependency property that can be evaluated at load time, the dependency property does not have to check for a reevaluated expression and can return the last effective value. This technique can be a performance benefit.
You want to change the underlying resource for all consumers, or you want to maintain separate writable instances for each consumer by using the x:Shared Attribute.
Static resource lookup behavior
The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.
The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.
Next, application resources are checked. Application resources are those resources within the resource dictionary that is defined by theApplication object for your WPF application.
Static resource references from within a resource dictionary must reference a resource that has already been defined lexically before the resource reference. Forward references cannot be resolved by a static resource reference. For this reason, if you use static resource references, you must design your resource dictionary structure such that resources intended for by-resource use are defined at or near the beginning of each respective resource dictionary.
Static resource lookup can extend into themes, or into system resources, but this is supported only because the XAML loader defers the request. The deferral is necessary so that the runtime theme at the time the page loads applies properly to the application. However, static resource references to keys that are known to only exist in themes or as system resources are not recommended. This is because such references are not reevaluated if the theme is changed by the user in realtime. A dynamic resource reference is more reliable when you request theme or system resources. The exception is when a theme element itself requests another resource. These references should be static resource references, for the reasons mentioned earlier.
The exception behavior if a static resource reference is not found varies. If the resource was deferred, then the exception occurs at runtime. If the resource was not deferred, the exception occurs at load time.
Dynamic Resources
Dynamic resources work best for the following circumstances:
The value of the resource depends on conditions that are not known until runtime. This includes system resources, or resources that are otherwise user settable. For example, you can create setter values that refer to system properties, as exposed by SystemColors,SystemFonts, or SystemParameters. These values are truly dynamic because they ultimately come from the runtime environment of the user and operating system. You might also have application-level themes that can change, where page-level resource access must also capture the change.
You are creating or referencing theme styles for a custom control.
You intend to adjust the contents of a ResourceDictionary during an application lifetime.
You have a complicated resource structure that has interdependencies, where a forward reference may be required. Static resource references do not support forward references, but dynamic resource references do support them because the resource does not need to be evaluated until runtime , and forward references are therefore not a relevant concept.
You are referencing a resource that is particularly large from the perspective of a compile or working set, and the resource might not be used immediately when the page loads. Static resource references always load from XAML when the page loads; however, a dynamic resource reference does not load until it is actually used.
You are creating a style where setter values might come from other values that are influenced by themes or other user settings.
You are applying resources to elements that might be reparented in the logical tree during application lifetime. Changing the parent also potentially changes the resource lookup scope, so if you want the resource for a reparented element to be reevaluated based on the new scope, always use a dynamic resource reference.
Dynamic resource lookup behavior
Resource lookup behavior for a dynamic resource reference parallels the lookup behavior in your code if you call FindResource orSetResourceReference.
The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.
The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.
Next, application resources are checked. Application resources are those resources within the resource dictionary that is defined by theApplication object for your WPF application.
Theme resource dictionary is checked, for the currently active theme. If the theme changes at runtime, the value is reevaluated.
System resources are checked.
Exception behavior (if any) varies:
If a resource was requested by a FindResource call, and was not found, an exception is raised.
If a resource was requested by a TryFindResource call, and was not found, no exception is raised, but the returned value is null. If the property being set does not accept null, then it is still possible that a deeper exception will be raised (this depends on the individual property being set).
If a resource was requested by a dynamic resource reference in XAML, and was not found, then the behavior depends on the general property system, but the general behavior is as if no property setting operation occurred at the level where the resource exists. For instance, if you attempt to set the background on a an individual button element using a resource that could not be evaluated, then no value set results, but the effective value can still come from other participants in the property system and value precedence. For instance, the background value might still come from a locally defined button style, or from the theme style. For properties that are not defined by theme styles, the effective value after a failed resource evaluation might come from the default value in the property metadata.
Restrictions
Dynamic resource references have some notable restrictions. At least one of the following must be true:
The property being set must be a property on a FrameworkElement or FrameworkContentElement. That property must be backed by aDependencyProperty.
The property being set must be a property on a Freezable that is provided as a value of either a FrameworkElement orFrameworkContentElement property, or a Setter value.
Because the property being set must be a DependencyProperty or Freezable property, most property changes can propagate to UI because a property change (the changed dynamic resource value) is acknowledged by the property system. Most controls include logic that will force another layout of a control if a DependencyProperty changes and that property might affect layout. However, not all properties that have aDynamicResource Markup Extension as their value are guaranteed to provide the value in such a way that they update in realtime in the UI. That functionality still might vary depending on the property, as well as depending on the type that owns the property, or even the logical structure of your application.
Styles, DataTemplates, and Implicit Keys
Earlier, it was stated that all items in a ResourceDictionary must have a key. However, that does not mean that all resources must have an explicitx:Key. Several object types support an implicit key when defined as a resource, where the key value is tied to the value of another property. This is known as an implicit key, whereas an x:Key attribute is an explicit key. You can overwrite any implicit key by specifying an explicit key.
One very important scenario for resources is when you define a Style. In fact, a Style is almost always defined as an entry in a resource dictionary, because styles are inherently intended for reuse. For more information about styles, see Styling and Templating.
Styles for controls can be both created with and referenced with an implicit key. The theme styles that define the default appearance of a control rely on this implicit key. The implicit key from the standpoint of requesting it is the Type of the control itself. The implicit key from the standpoint of defining the resource is the TargetType of the style. Therefore, if you are creating themes for custom controls, creating styles that interact with existing theme styles, you do not need to specify an x:Key Directive for that Style. And if you want to use the themed styles, you do not need to specify any style at all. For instance, the following style definition works, even though the Style resource does not appear to have a key:
<Style TargetType="Button"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush> <GradientStop Offset="0.0" Color="AliceBlue"/> <GradientStop Offset="1.0" Color="Salmon"/> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="FontSize" Value="18"/> </Style>
That style really does have a key: the implicit key typeof(Button). In markup, you can specify a TargetType directly as the type name (or you can optionally use {x:Type...} to return a Type.
Through the default theme style mechanisms used by WPF, that style is applied as the runtime style of a Button on the page, even though the Buttonitself does not attempt to specify its Style property or a specific resource reference to the style. Your style defined in the page is found earlier in the lookup sequence earlier than the theme dictionary style, using the same key that the theme dictionary style has. You could just specify<Button>Hello</Button> anywhere in the page, and the style you defined with TargetType of Button would apply to that button. If you want, you can still explicitly key the style with the same type value as TargetType, for clarity in your markup, but that is optional.
Implicit keys for styles do not apply on a control if OverridesDefaultStyle is true (also note that OverridesDefaultStyle might be set as part of native behavior for the control class, rather than explicitly on an instance of the control). Also, in order to support implicit keys for derived class scenarios, the control must override DefaultStyleKey (all existing controls provided as part of WPF do this). For more information about styles, themes, and control design, see Guidelines for Designing Stylable Controls.
DataTemplate also has an implicit key. The implicit key for a DataTemplate is the DataType property value. DataType can also be specified as the name of the type rather than explicitly using {x:Type...}. For details, see Data Templating Overview.
Resources and Code
This overview concentrates on how Windows Presentation Foundation (WPF) resources can be accessed or created using code rather than Extensible Application Markup Language (XAML) syntax. For more information on general resource usage and resources from a XAML syntax perspective, see XAML Resources.
Accessing Resources from Code
The keys that identify resources if they are defined through XAML are also used to retrieve specific resources if you request the resource in code. The simplest way to retrieve a resource from code is to call either the FindResource or the TryFindResource method from framework-level objects in your application. The behavioral difference between these methods is what happens if the requested key is not found. FindResource raises an exception; TryFindResource will not raise an exception but returns null. Each method takes the resource key as an input parameter, and returns a loosely typed object. Typically, a resource key is a string, but there are occasional nonstring usages; see the Using Objects as Keys section for details. Typically you would cast the returned object to the type required by the property that you are setting when requesting the resource. The lookup logic for code resource resolution is the same as the dynamic resource reference XAML case. The search for resources starts from the calling element, then continues to successive parent elements in the logical tree. The lookup continues onwards into application resources, themes, and system resources if necessary. A code request for a resource will properly account for runtime changes in resource dictionaries that might have been made subsequent to that resource dictionary being loaded from XAML, and also for realtime system resource changes.
The following is a brief code example that finds a resource by key and uses the returned value to set a property, implemented as a Click event handler.
void SetBGByResource(object sender, RoutedEventArgs e) { Button b = sender as Button; b.Background = (Brush)this.FindResource("RainbowBrush"); }
An alternative method for assigning a resource reference is SetResourceReference. This method takes two parameters: the key of the resource, and the identifier for a particular dependency property that is present on the element instance to which the resource value should be assigned. Functionally, this method is the same and has the advantage of not requiring any casting of return values.
Still another way to access resources programmatically is to access the contents of the Resources property as a dictionary. Accessing the dictionary contained by this property is also how you can add new resources to existing collections, check to see if a given key name is already taken in the collection, and other dictionary/collection operations. If you are writing a WPF application entirely in code, you can also create the entire collection in code, assign keys to it, and then assign the finished collection to the Resources property of an established element. This will be described in the next section.
You can index within any given Resources collection, using a specific key as the index, but you should be aware that accessing the resource in this way does not follow the normal runtime rules of resource resolution. You are only accessing that particular collection. Resource lookup will not be traversing the scope to the root or the application if no valid object was found at the requested key. However, this approach may have performance advantages in some cases precisely because the scope of the search for the key is more constrained. See the ResourceDictionary class for more details on how to work with the resource dictionary directly.
Creating Resources with Code
If you want to create an entire WPF application in code, you might also want to create any resources in that application in code. To achieve this, create a new ResourceDictionary instance, and then add all the resources to the dictionary using successive calls to ResourceDictionary.Add. Then, use the ResourceDictionary thus created to set the Resources property on an element that is present in a page scope, or the Application.Resources. You could also maintain the ResourceDictionary as a standalone object without adding it to an element. However, if you do this, you must access the resources within it by item key, as if it were a generic dictionary. A ResourceDictionary that is not attached to an element Resources property would not exist as part of the element tree and has no scope in a lookup sequence that can be used by FindResource and related methods.
Using Objects as Keys
Most resource usages will set the key of the resource to be a string. However, various WPF features deliberately do not use a string type to specify keys, instead this parameter is an object. The capability of having the resource be keyed by an object is used by the WPF style and theming support. The styles in themes which become the default style for an otherwise non-styled control are each keyed by the Type of the control that they should apply to. Being keyed by type provides a reliable lookup mechanism that works on default instances of each control type, and type can be detected by reflection and used for styling derived classes even though the derived type otherwise has no default style. You can specify a Type key for a resource defined in XAML by using the x:Type Markup Extension. Similar extensions exist for other nonstring key usages that support WPF features, such as ComponentResourceKey Markup Extension.
Merged Resource Dictionaries
Windows Presentation Foundation (WPF) resources support a merged resource dictionary feature. This feature provides a way to define the resources portion of a WPF application outside of the compiled XAML application. Resources can then be shared across applications and are also more conveniently isolated for localization.
Introducing a Merged Resource Dictionary
In markup, you use the following syntax to introduce a merged resource dictionary into a page:
<Page.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="myresourcedictionary.xaml"/> <ResourceDictionary Source="myresourcedictionary2.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Page.Resources>
Note that the ResourceDictionary element does not have an x:Key Directive, which is generally required for all items in a resource collection. But another ResourceDictionary reference within the MergedDictionaries collection is a special case, reserved for this merged resource dictionary scenario. The ResourceDictionary that introduces a merged resource dictionary cannot have an x:Key Directive. Typically, each ResourceDictionarywithin the MergedDictionaries collection specifies a Source attribute. The value of Source should be a uniform resource identifier (URI) that resolves to the location of the resources file to be merged. The destination of that URI must be another XAML file, with ResourceDictionary as its root element.
Note |
---|
It is legal to define resources within a ResourceDictionary that is specified as a merged dictionary, either as an alternative to specifying Source, or in addition to whatever resources are included from the specified source. However, this is not a common scenario; the main scenario for merged dictionaries is to merge resources from external file locations. If you want to specify resources within the markup for a page, you should typically define these in the main ResourceDictionary and not in the merged dictionaries. |
Merged Dictionary Behavior
Resources in a merged dictionary occupy a location in the resource lookup scope that is just after the scope of the main resource dictionary they are merged into. Although a resource key must be unique within any individual dictionary, a key can exist multiple times in a set of merged dictionaries. In this case, the resource that is returned will come from the last dictionary found sequentially in the MergedDictionaries collection. If the MergedDictionaries collection was defined in XAML, then the order of the merged dictionaries in the collection is the order of the elements as provided in the markup. If a key is defined in the primary dictionary and also in a dictionary that was merged, then the resource that is returned will come from the primary dictionary. These scoping rules apply equally for both static resource references and dynamic resource references.
Merged Dictionaries and Code
Merged dictionaries can be added to a Resources dictionary through code. The default, initially empty ResourceDictionary that exists for any Resources property also has a default, initially empty MergedDictionaries collection property. To add a merged dictionary through code, you obtain a reference to the desired primary ResourceDictionary, get its MergedDictionaries property value, and call Add on the generic Collectionthat is contained in MergedDictionaries. The object you add must be a new ResourceDictionary. In code, you do not set the Source property. Instead, you must obtain a ResourceDictionary object by either creating one or loading one. One way to load an existing ResourceDictionary to call XamlReader.Load on an existing XAML file stream that has a ResourceDictionary root, then casting the XamlReader.Load return value to ResourceDictionary.
Merged Resource Dictionary URIs
There are several techniques for how to include a merged resource dictionary, which are indicated by the uniform resource identifier (URI) format that you will use. Broadly speaking, these techniques can be divided into two categories: resources that are compiled as part of the project, and resources that are not compiled as part of the project.
For resources that are compiled as part of the project, you can use a relative path that refers to the resource location. The relative path is evaluated during compilation. Your resource must be defined as part of the project as a Resource build action. If you include a resource .xaml file in the project as Resource, you do not need to copy the resource file to the output directory, the resource is already included within the compiled application. You can also use Content build action, but you must then copy the files to the output directory and also deploy the resource files in the same path relationship to the executable.
Note |
---|
Do not use the Embedded Resource build action. The build action itself is supported for WPF applications, but the resolution of Source does not incorporate ResourceManager, and thus cannot separate the individual resource out of the stream. You could still use Embedded Resource for other purposes so long as you also used ResourceManager to access the resources. |
A related technique is to use a Pack URI to a XAML file, and refer to it as Source. Pack URI enables references to components of referenced assemblies and other techniques. For more information on Pack URIs, see WPF Application Resource, Content, and Data Files.
For resources that are not compiled as part of the project, the URI is evaluated at run time. You can use a common URI transport such as file: or http: to refer to the resource file. The disadvantage of using the noncompiled resource approach is that file: access requires additional deployment steps, and http: access implies the Internet security zone.
Reusing Merged Dictionaries
You can reuse or share merged resource dictionaries between applications, because the resource dictionary to merge can be referenced through any valid uniform resource identifier (URI). Exactly how you do this will depend on your application deployment strategy and which application model you follow. The aforementioned Pack URI strategy provides a way to commonly source a merged resource across multiple projects during development by sharing an assembly reference. In this scenario the resources are still distributed by the client, and at least one of the applications must deploy the referenced assembly. It is also possible to reference merged resources through a distributed URI that uses the http protocol.
Writing merged dictionaries as local application files or to local shared storage is another possible merged dictionary / application deployment scenario.
Localization
If resources that need to be localized are isolated to dictionaries that are merged into primary dictionaries, and kept as loose XAML, these files can be localized separately. This technique is a lightweight alternative to localizing the satellite resource assemblies. For details, see WPF Globalization and Localization Overview.
How-to Topics
How to: Define and Reference a Resource
This example shows how to define a resource and reference it by using an attribute in Extensible Application Markup Language (XAML).
Example
The following example defines two types of resources: a SolidColorBrush resource, and several Style resources. The SolidColorBrush resource MyBrush is used to provide the value of several properties that each take a Brush type value. The Style resources PageBackground, TitleText and Label each target a particular control type. The styles set a variety of different properties on the targeted controls, when that style resource is referenced by resource key and is used to set the Style property of several specific control elements defined in XAML.
Note that one of the properties within the setters of the Label style also references the MyBrush resource defined earlier. This is a common technique, but it is important to remember that resources are parsed and entered into a resource dictionary in the order that they are given. Resources are also requested by the order found within the dictionary if you use the StaticResource Markup Extension to reference them from within another resource. Make sure that any resource that you reference is defined earlier within the resources collection than where that resource is then requested. If necessary, you can work around the strict creation order of resource refererences by using a DynamicResource Markup Extension to reference the resource at runtime instead, but you should be aware that this DynamicResource technique has performance consequences. For details, see XAML Resources.
<Page Name="root" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Page.Resources> <SolidColorBrush x:Key="MyBrush" Color="Gold"/> <Style TargetType="Border" x:Key="PageBackground"> <Setter Property="Background" Value="Blue"/> </Style> <Style TargetType="TextBlock" x:Key="TitleText"> <Setter Property="Background" Value="Blue"/> <Setter Property="DockPanel.Dock" Value="Top"/> <Setter Property="FontSize" Value="18"/> <Setter Property="Foreground" Value="#4E87D4"/> <Setter Property="FontFamily" Value="Trebuchet MS"/> <Setter Property="Margin" Value="0,40,10,10"/> </Style> <Style TargetType="TextBlock" x:Key="Label"> <Setter Property="DockPanel.Dock" Value="Right"/> <Setter Property="FontSize" Value="8"/> <Setter Property="Foreground" Value="{StaticResource MyBrush}"/> <Setter Property="FontFamily" Value="Arial"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="Margin" Value="0,3,10,0"/> </Style> </Page.Resources> <StackPanel> <Border Style="{StaticResource PageBackground}"> <DockPanel> <TextBlock Style="{StaticResource TitleText}">Title</TextBlock> <TextBlock Style="{StaticResource Label}">Label</TextBlock> <TextBlock DockPanel.Dock="Top" HorizontalAlignment="Left" FontSize="36" Foreground="{StaticResource MyBrush}" Text="Text" Margin="20" /> <Button DockPanel.Dock="Top" HorizontalAlignment="Left" Height="30" Background="{StaticResource MyBrush}" Margin="40">Button</Button> <Ellipse DockPanel.Dock="Top" HorizontalAlignment="Left" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="40" /> </DockPanel> </Border> </StackPanel> </Page>
How to: Use Application Resources
This example shows how to use application resources.
Example
The following example shows an application definition file. The application definition file defines a resource section (a value for the Resources property). Resources defined at the application level can be accessed by all other pages that are part of the application. In this case, the resource is a declared style. Because a complete style that includes a control template can be lengthy, this example omits the control template that is defined within theContentTemplate property setter of the style.
<Application.Resources> <Style TargetType="Button" x:Key="GelButton" > <Setter Property="Margin" Value="1,2,1,2"/> <Setter Property="HorizontalAlignment" Value="Left"/> <Setter Property="Template"> <Setter.Value>
</Setter.Value> </Setter> </Style> </Application.Resources>
The following example shows a XAML page that references the application-level resource that the previous example defined. The resource is referenced by using a StaticResource Markup Extension that specifies the unique resource key for the requested resource. No resource with key of "GelButton" is found in the current page, so the resource lookup scope for the requested resource continues beyond the current page and into the defined application-level resources.
<StackPanel Name="root" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Button Height="50" Width="250" Style="{StaticResource GelButton}" Content="Button 1" /> <Button Height="50" Width="250" Style="{StaticResource GelButton}" Content="Button 2" /> </StackPanel>
How to: Use SystemFonts
This example shows how to use the static resources of the SystemFonts class in order to style or customize a button.
Example
System resources expose several system-determined values as both resources and properties in order to help you create visuals that are consistent with system settings. SystemFonts is a class that contains both system font values as static properties, and properties that reference resource keys that can be used to access those values dynamically at run time. For example, CaptionFontFamily is a SystemFonts value, and CaptionFontFamilyKey is a corresponding resource key.
In XAML, you can use the members of SystemFonts as either static properties or dynamic resource references (with the static property value as the key). Use a dynamic resource reference if you want the font metric to automatically update while the application runs; otherwise, use a static value reference.
Note |
---|
The resource keys have the suffix "Key" appended to the property name. |
The following example shows how to access and use the properties of SystemFonts as static values in order to style or customize a button. This markup example assigns SystemFonts values to a button.
<Button Margin="10, 10, 5, 5" Grid.Column="0" Grid.Row="3" FontSize="{x:Static SystemFonts.IconFontSize}" FontWeight="{x:Static SystemFonts.MessageFontWeight}" FontFamily="{x:Static SystemFonts.CaptionFontFamily}"> SystemFonts </Button>
To use the values of SystemFonts in code, you do not have to use either a static value or a dynamic resource reference. Instead, use the non-key properties of the SystemFonts class. Although the non-key properties are apparently defined as static properties, the run-time behavior of WPF as hosted by the system will reevaluate the properties in real time and will properly account for user-driven changes to system values. The following example shows how to specify the font settings of a button.
Button btncsharp = new Button(); btncsharp.Content = "SystemFonts"; btncsharp.Background = SystemColors.ControlDarkDarkBrush; btncsharp.FontSize = SystemFonts.IconFontSize; btncsharp.FontWeight = SystemFonts.MessageFontWeight; btncsharp.FontFamily = SystemFonts.CaptionFontFamily; cv1.Children.Add(btncsharp);
How to: Use System Fonts Keys
System resources expose a number of system metrics as resources to help developers create visuals that are consistent with system settings.SystemFonts is a class that contains both system font values and system font resources that bind to the values—for example, CaptionFontFamily andCaptionFontFamilyKey.
System font metrics can be used as either static or dynamic resources. Use a dynamic resource if you want the font metric to update automatically while the application runs; otherwise use a static resource.
Note |
---|
Dynamic resources have the keyword Key appended to the property name. |
The following example shows how to access and use system font dynamic resources to style or customize a button. This XAML example creates a button style that assigns SystemFonts values to a button.
Example
<Style x:Key="SimpleFont" TargetType="{x:Type Button}"> <Setter Property = "FontSize" Value= "{DynamicResource {x:Static SystemFonts.IconFontSizeKey}}"/> <Setter Property = "FontWeight" Value= "{DynamicResource {x:Static SystemFonts.MessageFontWeightKey}}"/> <Setter Property = "FontFamily" Value= "{DynamicResource {x:Static SystemFonts.CaptionFontFamilyKey}}"/> </Style>
How to: Use SystemParameters
This example shows how to access and use the properties of SystemParameters in order to style or customize a button.
Example
System resources expose several system based settings as resources in order to help you create visuals that are consistent with system settings.SystemParameters is a class that contains both system parameter value properties, and resource keys that bind to the values. For example,FullPrimaryScreenHeight is a SystemParameters property value and FullPrimaryScreenHeightKey is the corresponding resource key.
In XAML, you can use the members of SystemParameters as either a static property usage, or a dynamic resource references (with the static property value as the key). Use a dynamic resource reference if you want the system based value to update automatically while the application runs; otherwise, use a static reference. Resource keys have the suffix Key appended to the property name.
The following example shows how to access and use the static values of SystemParameters to style or customize a button. This markup example sizes a button by applying SystemParameters values to a button.
<Button FontSize="8" Margin="10, 10, 5, 5" Grid.Column="0" Grid.Row="5" HorizontalAlignment="Left" Height="{x:Static SystemParameters.CaptionHeight}" Width="{x:Static SystemParameters.IconGridWidth}"> SystemParameters </Button>
To use the values of SystemParameters in code, you do not have to use either static references or dynamic resource references. Instead, use the values of the SystemParameters class. Although the non-key properties are apparently defined as static properties, the runtime behavior of WPF as hosted by the system will reevaluate the properties in realtime, and will properly account for user-driven changes to system values. The following example shows how to set the width and height of a button by using SystemParameters values.
How to: Use System Parameters Keys
System resources expose a number of system metrics as resources to help developers create visuals that are consistent with system settings.SystemParameters is a class that contains both system parameter values and resource keys that bind to the values—for example,FullPrimaryScreenHeight and FullPrimaryScreenHeightKey. System parameter metrics can be used as either static or dynamic resources. Use a dynamic resource if you want the parameter metric to update automatically while the application runs; otherwise use a static resource.
Note |
---|
Dynamic resources have the keyword Key appended to the property name. |
The following example shows how to access and use system parameter dynamic resources to style or customize a button. This XAML example sizes a button by assigning SystemParameters values to the button's width and height.
Example
<Style x:Key="SimpleParam" TargetType="{x:Type Button}"> <Setter Property = "Height" Value= "{DynamicResource {x:Static SystemParameters.CaptionHeightKey}}"/> <Setter Property = "Width" Value= "{DynamicResource {x:Static SystemParameters.IconGridWidthKey}}"/> </Style>
'프로그래밍 > WPF' 카테고리의 다른 글
Globalization and Localization (0) | 2016.11.05 |
---|---|
Documents (0) | 2016.11.05 |
Events (0) | 2016.11.01 |
Element Tree and Serialization (0) | 2016.11.01 |
Base Elements (기본 요소) (0) | 2016.10.24 |