Application.FindResource(Object) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
public:
System::Object ^ FindResource(System::Object ^ resourceKey);
public object FindResource (object resourceKey);
member this.FindResource : obj -> obj
Public Function FindResource (resourceKey As Object) As Object
參數
- resourceKey
- Object
要尋找之資源的名稱。
傳回
要求的資源物件。 如果找不到要求的資源,則會擲回 ResourceReferenceKeyNotFoundException。
例外狀況
範例
下列範例示範如何使用 FindResource 來尋找資源,以及在找不到資源時處理 ResourceReferenceKeyNotFoundException 。
void findResourceButton_Click(object sender, RoutedEventArgs e) {
try {
object resource = Application.Current.FindResource("UnfindableResource");
}
catch (ResourceReferenceKeyNotFoundException ex) {
MessageBox.Show("Resource not found.");
}
}
Private Sub findResourceButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Try
Dim resource As Object = Application.Current.FindResource("UnfindableResource")
Catch ex As ResourceReferenceKeyNotFoundException
MessageBox.Show("Resource not found.")
End Try
End Sub
備註
FindResource 會先查看指定資源的應用程式範圍資源。 應用程式範圍資源是由 Application 管理,並從 屬性公開 Resources 。 如果在一組應用程式範圍資源中找不到指定的資源, FindResource 則接下來會搜尋系統資源。 系統資源是由使用者定義的殼層資源,包括色彩、字型和殼層組態。 這些會分別從 SystemColors 、 SystemFonts 和 SystemParameters 類型公開為靜態屬性。 為了取得 FindResource 它們,這些類型也會公開設計要傳遞至 FindResource 的資源索引鍵屬性,例如 IconWidthKey 。
因為 FindResource 會傳回 物件,所以如果找到資源,您必須將傳回的值轉換成適當的類型。
重要
如果您針對找不到的索引鍵呼叫這個方法,則會擲回例外狀況。 如果您不想要處理呼叫 FindResource 所產生的例外狀況,請改為呼叫 TryFindResource ; TryFindResource 在找不到要求的資源時傳回參考,而且不會擲回 null
例外狀況。
此方法是安全線程,可以從任何執行緒呼叫。
適用於
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應