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.

適用於

另請參閱