FrameworkElement.FindResource(Object) 方法


搜索具有指定密钥的资源,如果未找到请求的资源,则会引发异常。Searches for a resource with the specified key, and throws an exception if the requested resource is not found.

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



所请求资源的键标识符。The key identifier for the requested resource.


所请求的资源。The requested resource. 如果未找到具有所提供键的资源,将引发异常。If no resource with the provided key was found, an exception is thrown. 在发生异常的情况下,可能还会返回一个 UnsetValue 值。An UnsetValue value might also be returned in the exception case.


找不到 resourceKey,且事件管理器对于 UnhandledException 事件不存在。resourceKey was not found and an event handler does not exist for the UnhandledException event.

-or- 找不到 resourceKey,且 Handled 属性在 UnhandledException 事件中为 falseresourceKey was not found and the Handled property is false in the UnhandledException event.

resourceKeynullresourceKey is null.


下面的示例获取命名资源,并将其转换为适当的类型以填充属性。The following example obtains a named resource and casts it to an appropriate type to fill a property.

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



如果对找不到的键调用此方法,则会引发异常。If you call this method for a key that cannot be found, an exception is thrown. 如果不想处理通过调用 FindResource而产生的异常,请改为调用 TryFindResourceIf you do not want to handle exceptions that result from calling FindResource, call TryFindResource instead. 当找不到请求的资源时,TryFindResource 返回 null,并且不会引发异常。TryFindResource returns null when a requested resource cannot be found, and does not throw an exception.

如果在调用元素上找不到该资源,将在下一步搜索逻辑树中的父元素,然后搜索应用程序,然后是主题,最后是系统资源。If the resource is not found on the calling element, the parent element in the logical tree is searched next, then the application, then themes, and finally system resources. 此查找方法与在标记中动态资源引用请求资源时搜索树的方式相同。This lookup methodology is identical to how the tree is searched if a resource were requested by a dynamic resource reference in markup. 有关资源查找的详细信息,请参阅XAML 资源For more information about resource lookup, see XAML Resources.

通常,您会立即将 FindResource 返回值强制转换为使用返回的资源值设置的属性的类型。Typically, you immediately cast a FindResource return value to the type of the property that you setting with the returned resource value.

资源键不一定是字符串。Resource keys are not necessarily strings. 例如,主题级别的控件样式被有意地键控到控件的 Type 中,控件的应用程序或页面样式通常使用此相同的键约定。For instance, styles for controls at the theme level are deliberately keyed to the Type of the control, and application or page styles for controls typically use this same key convention. 有关详细信息,请参阅样式设置和模板化XAML 资源For details, see Styling and Templating or XAML Resources.