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.

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 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.

適用於

另請參閱