ResourceContext Classe

Definição

Encapsula todos os fatores (ResourceQualifiers) que podem afetar a seleção de recursos.

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
Herança
Object Platform::Object IInspectable ResourceContext
Atributos

Requisitos do Windows

Família de dispositivos
Windows 10 (introduzida na 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduzida na v1.0)

Exemplos

Este exemplo baseia-se no cenário 12 dos recursos de aplicativo e no exemplo de localização. Consulte o exemplo para obter a solução 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;
    });
}

Comentários

Os recursos podem ser sensíveis à escala, e diferentes exibições pertencentes a um aplicativo podem ser exibidas simultaneamente em diferentes dispositivos de exibição, que podem usar diferentes escalas. Por esse motivo, um ResourceContext geralmente está associado a uma exibição específica e deve ser obtido usando GetForCurrentView. (Um ResourceContext independente de exibição pode ser obtido usando GetForViewIndependentUse, mas observe que a funcionalidade dependente de escala falhará se for invocada em um ResourceContext que não esteja associado a uma exibição.)

Não crie uma instância do ResourceContext usando o construtor, pois ela está preterida e sujeita à remoção em uma versão futura.

Exceto quando indicado de outra forma, os métodos dessa classe podem ser chamados em qualquer thread.

Histórico de versão

Versão do Windows Versão do SDK Valor adicionado
1903 18362 GetForUIContext

Construtores

ResourceContext()

Cria um objeto ResourceContext clonado.

Observação

O construtor ResourceContext pode ser alterado ou indisponível para versões após Windows 8.1. Em vez disso, use GetForCurrentView e Clone.

Propriedades

Languages

Obtém ou define o qualificador de idioma para esse contexto.

QualifierValues

Obtém um mapa gravável e observável de todos os qualificadores com suporte, indexados por nome.

Métodos

Clone()

Cria um clone desse ResourceContext, com qualificadores idênticos.

CreateMatchingContext(IIterable<ResourceQualifier>)

Cria um novo ResourceContext que corresponde a um conjunto fornecido de qualificadores.

Observação

CreateMatchingContext pode ser alterado ou indisponível para versões após Windows 8.1. Em vez disso, use ResourceContext.GetForCurrentView.OverrideToMatch.

GetForCurrentView()

Obtém um ResourceContext padrão associado à exibição atual do aplicativo em execução no momento.

GetForUIContext(UIContext)

Obtém um ResourceContext padrão associado ao UIContext especificado para o aplicativo em execução no momento.

GetForViewIndependentUse()

Obtém um ResourceContext padrão não associado a nenhuma exibição.

OverrideToMatch(IIterable<ResourceQualifier>)

Substitui os valores do qualificador fornecidos por esse contexto para corresponder a uma lista especificada de ResourceQualifiers resolvidos. Normalmente, os ResourceQualifierresolvidos são associados a um recurso que foi pesquisado anteriormente.

Reset()

Redefine os valores substituídos para todos os qualificadores na instância ResourceContext fornecida.

Reset(IIterable<String>)

Redefine os valores substituídos para os qualificadores especificados na instância ResourceContext especificada.

ResetGlobalQualifierValues()

Remove todas as substituições de qualificador de contextos padrão de todas as exibições em todo o aplicativo.

ResetGlobalQualifierValues(IIterable<String>)

Remove as substituições do qualificador para os qualificadores especificados dos contextos padrão de todos os modos de exibição em todo o aplicativo.

SetGlobalQualifierValue(String, String)

Aplica uma única substituição de valor qualificador a contextos padrão de todas as exibições para o aplicativo atual.

SetGlobalQualifierValue(String, String, ResourceQualifierPersistence)

Aplica uma única substituição de valor qualificador a contextos padrão de todas as exibições para o aplicativo atual e especifica a persistência da substituição.

Aplica-se a

Confira também