Partilhar via


Como: recuperar recursos no código

Logical resources embedded in your XAML markup can be accessed and used in code. Every Windows Presentation Foundation (WPF) control exposes its resources in a collection named Resources, and also exposes a method named FindResource that can be used to retrieve a reference to an individual resource. You can retrieve resources by using the FindResource method or by directly accessing the Resources collection.

To access resources in code by using the FindResource method

  • Use the FindResource method to obtain a reference to a named resource that is defined in the XAML markup for the control or window. The following example demonstrates how to obtain a reference to a SolidColorBrush named myBrush defined as a resource in the current window.

    Dim aBrush As SolidColorBrush
    aBrush = CType(Me.FindResource("myBrush"), SolidColorBrush)
    
    SolidColorBrush aBrush;
    aBrush = (SolidColorBrush)this.FindResource("myBrush");
    
    ObservaçãoObservação

    If a resource cannot be found, FindResource throws an exception. You can avoid having an exception thrown if a resource cannot be found by using the TryFindResource method instead, which returns a null value if a resource cannot be found.

To access resources in code by using the Resources collection

  • Retrieve the resource from the Resources collection using the name of the resource. The following example demonstrates how to obtain a reference to a SolidColorBrush named myBrush defined as a resource in the current window.

    Dim aBrush As SolidColorBrush
    aBrush = CType(Me.Resources("myBrush"), SolidColorBrush)
    
    SolidColorBrush aBrush;
    aBrush = (SolidColorBrush)this.Resources["myBrush"];
    

Consulte também

Tarefas

Como: Get and Set Application-Scope Resources

Conceitos

Visão geral sobre Recursos

Recursos e código

Outros recursos

Usando recursos