Windows apps
Collapse the table of content
Expand the table of content
Information
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

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

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

public Object TryFindResource (
	Object resourceKey
)
public Object TryFindResource (
	Object resourceKey
)
public function TryFindResource (
	resourceKey : Object
) : Object
You cannot use methods in XAML.

Parameters

resourceKey

Key identifier of the resource to be found.

Return Value

The found resource. If no resource was found, a null reference (Nothing in Visual Basic) will be returned.

If the resource is not found on the calling element, the parent tree is searched by using the logical tree, in the same way that the tree would be searched if a resource were requested by key at runtime.

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 will raise 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).

void TryFind(object sender, RoutedEventArgs e)  {
    Button b = e.Source as Button;
    b.Background = (Brush)b.TryFindResource("customBrush");
}    

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0

Community Additions

Show:
© 2017 Microsoft