ResourceContext Class

Definition

Encapsulates all of the factors (ResourceQualifiers) that might affect resource selection.

public ref class ResourceContext sealed
/// [Windows.Foundation.Metadata.Activatable(65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class ResourceContext final
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
/// [Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
class ResourceContext final
[Windows.Foundation.Metadata.Activatable(65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class ResourceContext
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
[Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
public sealed class ResourceContext
function ResourceContext()
Public NotInheritable Class ResourceContext
Inheritance
Object Platform::Object IInspectable ResourceContext
Attributes

Windows requirements

Device family
Windows 10 (introduced in 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced in v1.0)

Examples

This example is based on scenario 12 of the Application resources and localization sample. See the sample for the complete solution.

private async void Scenario12Button_Show_Click(object sender, RoutedEventArgs e)
{
    // Two coding patterns will be used:
    //   1. Get a ResourceContext on the UI thread using GetForCurrentView and pass 
    //      to the non-UI thread
    //   2. Get a ResourceContext on the non-UI thread using GetForViewIndependentUse
    //
    // Two analogous patterns could be used for ResourceLoader instead of ResourceContext.

    // pattern 1: get a ResourceContext for the UI thread
    ResourceContext defaultContextForUiThread = ResourceContext.GetForCurrentView();

    // pattern 2: we'll create a view-independent context in the non-UI worker thread

    // We need some things in order to display results in the UI (doing that
    // for purposes of this sample, to show that work was actually done in the
    // worker thread):
    List<string> uiDependentResourceList = new List<string>();
    List<string> uiIndependentResourceList = new List<string>();

    // use a worker thread for the heavy lifting so the UI isn't blocked
    await Windows.System.Threading.ThreadPool.RunAsync(
        (source) =>
        {
            ResourceMap stringResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            // pattern 1: the defaultContextForUiThread variable was created above and is visible here

            // pattern 2: get a view-independent ResourceContext
            ResourceContext defaultViewIndependentResourceContext = ResourceContext.GetForViewIndependentUse();

            // NOTE: The ResourceContext obtained using GetForViewIndependentUse() has no scale qualifier
            // value set. If this ResourceContext is used in its default state to retrieve a resource, that 
            // will work provided that the resource does not have any scale-qualified variants. But if the
            // resource has any scale-qualified variants, then that will fail at runtime.
            //
            // A scale qualifier value on this ResourceContext can be set programmatically. If that is done,
            // then the ResourceContext can be used to retrieve a resource that has scale-qualified variants.
            // But if the scale qualifier is reset (e.g., using the ResourceContext.Reset() method), then
            // it will return to the default state with no scale qualifier value set, and cannot be used
            // to retrieve any resource that has scale-qualified variants.

            // simulate processing a number of items
            // just using a single string resource: that's sufficient to demonstrate 
            for (var i = 0; i < 4; i++)
            {
                // pattern 1: use the ResourceContext from the UI thread
                string listItem1 = stringResourceMap.GetValue("string1", defaultContextForUiThread).ValueAsString;
                uiDependentResourceList.Add(listItem1);

                // pattern 2: use the view-independent ResourceContext
                string listItem2 = stringResourceMap.GetValue("string1", defaultViewIndependentResourceContext).ValueAsString;
                uiIndependentResourceList.Add(listItem2);
            }
        });

    // Display the results in one go. (A more finessed design might add results
    // in the UI asynchronously, but that goes beyond what this sample is 
    // demonstrating.)
    ViewDependentResourcesList.ItemsSource = uiDependentResourceList;
    ViewIndependentResourcesList.ItemsSource = uiIndependentResourceList;
}
void Scenario12::Scenario12Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    // Two coding patterns will be used:
    //   1. Get a ResourceContext on the UI thread using GetForCurrentView and pass 
    //      to the non-UI thread
    //   2. Get a ResourceContext on the non-UI thread using GetForViewIndependentUse
    //
    // Two analogous patterns could be used for ResourceLoader instead of ResourceContext.

    // pattern 1: get a ResourceContext for the UI thread
    ResourceContext^ defaultContextForUiThread = ResourceContext::GetForCurrentView();

    // pattern 2: we'll create a view-independent context in the non-UI worker thread

    // We need some things in order to display results in the UI (doing that
    // for purposes of this sample, to show that work was actually done in the
    // worker thread): a pair of vectors to capture data, and a pair of variable 
    // references to the controls where the results will be displayed (needed to
    // pass to the .then lambda).
    Platform::Collections::Vector<Platform::String^>^ uiDependentResourceItems = ref new Platform::Collections::Vector<Platform::String^>();
    Platform::Collections::Vector<Platform::String^>^ uiIndependentResourceItems = ref new Platform::Collections::Vector<Platform::String^>();
    ItemsControl^ viewDependentListControl = ViewDependentResourcesList;
    ItemsControl^ viewIndependentListControl = ViewIndependentResourcesList;


    // use a worker thread for the heavy lifting so the UI isn't blocked
    concurrency::create_task(
        Windows::System::Threading::ThreadPool::RunAsync(
            ref new Windows::System::Threading::WorkItemHandler(
            [defaultContextForUiThread, uiDependentResourceItems, uiIndependentResourceItems](Windows::Foundation::IAsyncAction^ /*action*/)
        {
            // This is happening asynchronously on a background worker thread,
            // not on the UI thread.
            ResourceMap^ stringResourceMap = ResourceManager::Current->MainResourceMap->GetSubtree("Resources");

            // coding pattern 1: the defaultContextForUiThread variable was created above and has been captured to use here

            // coding pattern 2: get a view-independent ResourceContext
            ResourceContext^ defaultViewIndependentResourceContext = ResourceContext::GetForViewIndependentUse();

            // NOTE: The ResourceContext obtained using GetForViewIndependentUse() has no scale qualifier
            // value set. If this ResourceContext is used in its default state to retrieve a resource, that 
            // will work provided that the resource does not have any scale-qualified variants. But if the
            // resource has any scale-qualified variants, then that will fail at runtime.
            //
            // A scale qualifier value on this ResourceContext can be set programmatically. If that is done,
            // then the ResourceContext can be used to retrieve a resource that has scale-qualified variants.
            // But if the scale qualifier is reset (e.g., using the ResourceContext::Reset() method), then
            // it will return to the default state with no scale qualifier value set, and cannot be used
            // to retrieve any resource that has scale-qualified variants.

            // simulate processing a number of items
            // just using a single string resource: that's sufficient to demonstrate 
            for (auto i = 0; i < 4; i++)
            {
                // pattern 1: use the ResourceContext from the UI thread
                Platform::String^ item1 = stringResourceMap->GetValue("string1", defaultContextForUiThread)->ValueAsString;
                uiDependentResourceItems->Append(item1);

                // pattern 2: use the view-independent ResourceContext
                Platform::String^ item2 = stringResourceMap->GetValue("string1", defaultViewIndependentResourceContext)->ValueAsString;
                uiIndependentResourceItems->Append(item2);
            }
        }))
    ).then([uiDependentResourceItems, uiIndependentResourceItems, viewDependentListControl, viewIndependentListControl]
    {
        // After the async work is complete, this will execute on the UI thread.

        // Display the results in one go. (A more finessed design might add results
        // in the UI asynchronously, but that goes beyond what this sample is 
        // demonstrating.)
        viewDependentListControl->ItemsSource = uiDependentResourceItems;
        viewIndependentListControl->ItemsSource = uiIndependentResourceItems;
    });
}

Remarks

Resources can be sensitive to scale, and different views owned by an app are able to display simultaneously on different display devices, which might use different scales. For that reason, a ResourceContext is generally associated with a specific view, and should be obtained using GetForCurrentView. (A view-independent ResourceContext can be obtained using GetForViewIndependentUse, but note that scale-dependent functionality will fail if invoked on a ResourceContext that is not associated with a view.)

Do not create an instance of ResourceContext using the constructor, as it is deprecated and subject to removal in a future release.

Except where otherwise noted, methods of this class can be called on any thread.

Version history

Windows version SDK version Value added
1903 18362 GetForUIContext

Constructors

ResourceContext()

Creates a cloned ResourceContext object.

Note

ResourceContext constructor may be altered or unavailable for releases after Windows 8.1. Instead, use GetForCurrentView and Clone.

Properties

Languages

Gets or sets the language qualifier for this context.

QualifierValues

Gets a writable, observable map of all supported qualifiers, indexed by name.

Methods

Clone()

Creates a clone of this ResourceContext, with identical qualifiers.

CreateMatchingContext(IIterable<ResourceQualifier>)

Creates a new ResourceContext that matches a supplied set of qualifiers.

Note

CreateMatchingContext may be altered or unavailable for releases after Windows 8.1. Instead, use ResourceContext.GetForCurrentView.OverrideToMatch.

GetForCurrentView()

Gets a default ResourceContext associated with the current view for the currently running application.

GetForUIContext(UIContext)

Gets a default ResourceContext associated with the specified UIContext for the currently running application.

GetForViewIndependentUse()

Gets a default ResourceContext not associated with any view.

OverrideToMatch(IIterable<ResourceQualifier>)

Overrides the qualifier values supplied by this context to match a specified list of resolved ResourceQualifiers. Typically the resolved ResourceQualifiers are associated with a resource that was looked up earlier.

Reset()

Resets the overridden values for all qualifiers on the given ResourceContext instance.

Reset(IIterable<String>)

Resets the overridden values for the specified qualifiers on the given ResourceContext instance.

ResetGlobalQualifierValues()

Removes any qualifier overrides from default contexts of all views across the app.

ResetGlobalQualifierValues(IIterable<String>)

Removes qualifier overrides for the specified qualifiers from default contexts of all views across the app.

SetGlobalQualifierValue(String, String)

Applies a single qualifier value override to default contexts of all views for the current app.

SetGlobalQualifierValue(String, String, ResourceQualifierPersistence)

Applies a single qualifier value override to default contexts of all views for the current app, and specifies the persistence of the override.

Applies to

See also