Windows apps
Collapse the table of content
Expand the table of content
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

FrameworkElement.TryFindResource Method (Object)


Searches for a resource with the specified key, and returns that resource if found.

Namespace:   System.Windows
Assembly:  PresentationFramework (in PresentationFramework.dll)

Public Function TryFindResource (
	resourceKey As Object
) As Object


Type: System.Object

The key identifier of the resource to be found.

Return Value

Type: System.Object

The found resource, or null if no resource with the provided key is found.

If the resource is not found on the calling element, the parent resource tree is searched upward through the logical tree, in the same way that the tree would be searched if a resource were requested by key at run time. The method returns null only if no resource of that key existed anywhere in the resource tree, per the existing conditions of the tree at the time that TryFindResource is called.

Typically you would immediately cast the return value to the type of the property that you were attempting to set with the returned resource value.

The FindResource method has similar behavior, except that it throws an exception if no resource with the provided key was returned.

The following example is implemented as a button handler, where the button being clicked sets its background to a resource-defined brush obtained by calling TryFindResource on itself. This walks the element tree and finds the resource (the resource itself is defined in XAML and is not shown).

Private Sub TryFind(ByVal sender As Object, ByVal e As RoutedEventArgs)
	Dim b As Button = TryCast(e.Source, Button)
	b.Background = CType(b.TryFindResource("customBrush"), Brush)
End Sub

.NET Framework
Available since 3.0
Return to top
© 2017 Microsoft