FrameworkContentElement.TryFindResource(Object) 方法


以指定的索引鍵搜尋資源;如果找到,則傳回該資源。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



要尋找之資源的索引鍵識別項。Key identifier of the resource to be found.


找到的資源。The found resource. 如果找不到資源,則會傳回 nullIf no resource was found, null is returned.


下列範例會尋找在標記中定義的資源,並將它套用至專案的特定屬性,以回應路由事件。The following example finds a resource as defined in markup and applies it to a certain property of an element in response to a routed event.

void SetBGByResourceTry(object sender, RoutedEventArgs e)
    Block b = sender as Block;
    b.Background = (Brush)this.TryFindResource("RainbowBrush");
Private Sub SetBGByResourceTry(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim b As Block = TryCast(sender, Block)
    b.Background = CType(Me.TryFindResource("RainbowBrush"), Brush)
End Sub


如果在呼叫的元素上找不到資源,則會使用邏輯樹狀結構搜尋父樹狀結構,方法是在執行時間以索引鍵要求動態資源參考時,搜尋樹狀結構。If the resource is not found on the calling element, the parent tree is searched using the logical tree, in the same way that the tree would be searched if a dynamic resource reference were requested by key at run-time.

一般來說,您會立即將傳回值轉換成您嘗試使用傳回的資源值來設定的屬性類型。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 will throw an exception in the case of not finding a resource with the provided key.