FrameworkElement.TryFindResource(Object) 方法

定义

搜索具有指定键的资源,如果找到,则返回该资源。Searches for a resource with the specified key, and returns that resource if found.

public:
 System::Object ^ TryFindResource(System::Object ^ resourceKey);
public object TryFindResource (object resourceKey);
member this.TryFindResource : obj -> obj
Public Function TryFindResource (resourceKey As Object) As Object

参数

resourceKey
Object

要查找的资源的键标识符。The key identifier of the resource to be found.

返回

找到的资源;如果未找到具有所提供 key 的资源,则为 nullThe found resource, or null if no resource with the provided key is found.

示例

下面的示例是作为按钮处理程序实现的,在该按钮处理程序中,单击的按钮会将其背景设置为通过对其自身调用 TryFindResource 获取的资源定义画笔。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. 这会遍历元素树并查找资源(资源本身在 XAMLXAML 中定义,并且不会显示)。This walks the element tree and finds the resource (the resource itself is defined in XAMLXAML and is not shown).

void TryFind(object sender, RoutedEventArgs e)  {
    Button b = e.Source as Button;
    b.Background = (Brush)b.TryFindResource("customBrush");
}    
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

注解

如果在调用元素上找不到该资源,则会通过逻辑树向上搜索父资源树,其方式与在运行时键请求资源时搜索树的方式相同。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. 仅当调用 TryFindResource 时,此方法将仅在资源树中的任何位置不存在该键的任何资源时返回 nullThe 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.

FindResource 方法的行为类似,不同之处在于,如果未返回具有所提供键的资源,则会引发异常。The FindResource method has similar behavior, except that it throws an exception if no resource with the provided key was returned.

适用于

另请参阅