FrameworkElement.TryFindResource(Object) FrameworkElement.TryFindResource(Object) FrameworkElement.TryFindResource(Object) FrameworkElement.TryFindResource(Object) Method


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

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


Object Object Object 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. 仅当资源null树中的任何位置都不存在该密钥的任何资源时, TryFindResource该方法才会返回。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.

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