Condividi tramite


ResourceContext Classe

Definizione

Incapsula tutti i fattori (ResourceQualifiers) che potrebbero influire sulla selezione delle risorse.

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
Ereditarietà
Object Platform::Object IInspectable ResourceContext
Attributi

Requisiti Windows

Famiglia di dispositivi
Windows 10 (è stato introdotto in 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (è stato introdotto in v1.0)

Esempio

Questo esempio si basa sullo scenario 12 delle risorse dell'applicazione e dell'esempio di localizzazione. Vedere l'esempio per la soluzione completa.

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;
    });
}

Commenti

Le risorse possono essere sensibili alla scalabilità e a visualizzazioni diverse di proprietà di un'app sono in grado di visualizzare simultaneamente in dispositivi di visualizzazione diversi, che potrebbero usare scalabilità diverse. Per questo motivo, un oggetto ResourceContext è in genere associato a una visualizzazione specifica e deve essere ottenuto usando GetForCurrentView. È possibile ottenere un oggetto ResourceContext indipendente dalla visualizzazione usando GetForViewIndependentUse, ma si noti che la funzionalità dipendente dalla scalabilità avrà esito negativo se richiamata in un oggetto ResourceContext non associato a una vista.

Non creare un'istanza di ResourceContext usando il costruttore, poiché è deprecata e soggetta alla rimozione in una versione futura.

Ad eccezione del caso indicato in caso contrario, i metodi di questa classe possono essere chiamati in qualsiasi thread.

Cronologia delle versioni

Versione di Windows Versione dell'SDK Valore aggiunto
1903 18362 GetForUIContext

Costruttori

ResourceContext()

Crea un oggetto ResourceContext clonato.

Nota

Il costruttore ResourceContext può essere modificato o non disponibile per le versioni dopo Windows 8.1. Usare invece GetForCurrentView e Clone.

Proprietà

Languages

Ottiene o imposta il qualificatore della lingua per questo contesto.

QualifierValues

Ottiene una mappa scrivibile e osservabile di tutti i qualificatori supportati, indicizzati in base al nome.

Metodi

Clone()

Crea un clone di resourceContext, con qualificatori identici.

CreateMatchingContext(IIterable<ResourceQualifier>)

Crea un nuovo oggetto ResourceContext che corrisponde a un set fornito di qualificatori.

Nota

CreateMatchingContext può essere modificato o non disponibile per le versioni dopo Windows 8.1. Usare invece ResourceContext.GetForCurrentView.OverrideToMatch.

GetForCurrentView()

Ottiene un oggetto ResourceContext predefinito associato alla visualizzazione corrente per l'applicazione attualmente in esecuzione.

GetForUIContext(UIContext)

Ottiene un oggetto ResourceContext predefinito associato all'interfaccia utente specificata per l'applicazione attualmente in esecuzione.

GetForViewIndependentUse()

Ottiene un oggetto ResourceContext predefinito non associato a alcuna visualizzazione.

OverrideToMatch(IIterable<ResourceQualifier>)

Esegue l'override dei valori del qualificatore forniti da questo contesto per corrispondere a un elenco specificato di ResourceQualifierrisolti. In genere, l'oggetto ResourceQualifierrisolto è associato a una risorsa cercata in precedenza.

Reset()

Reimposta i valori sottoposti a override per tutti i qualificatori nell'istanza di ResourceContext specificata.

Reset(IIterable<String>)

Reimposta i valori sottoposti a override per i qualificatori specificati nell'istanza di ResourceContext specificata.

ResetGlobalQualifierValues()

Rimuove eventuali sostituzioni del qualificatore da contesti predefiniti di tutte le visualizzazioni nell'app.

ResetGlobalQualifierValues(IIterable<String>)

Rimuove gli overridi del qualificatore per i qualificatori specificati dai contesti predefiniti di tutte le visualizzazioni nell'app.

SetGlobalQualifierValue(String, String)

Applica un singolo valore qualificatore override ai contesti predefiniti di tutte le visualizzazioni per l'app corrente.

SetGlobalQualifierValue(String, String, ResourceQualifierPersistence)

Applica un singolo valore qualificatore override ai contesti predefiniti di tutte le visualizzazioni per l'app corrente e specifica la persistenza dell'override.

Si applica a

Vedi anche