C# 从Window.Resources中的对象查找资源

C# 从Window.Resources中的对象查找资源,c#,wpf,xaml,C#,Wpf,Xaml,我在XAML中声明了一个资源,如下所示: <Window x:Class="Test.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Test" Title="MainWindow" Hei

我在XAML中声明了一个资源,如下所示:

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Test"
    Title="MainWindow" Height="350" Width="525" Name="form1">
  <Window.Resources>
    <ObjectDataProvider x:Key="SingleRole" ObjectType="{x:Type local:SingleRole}" />
  </Window.Resources>
...
</Window>

我该怎么做?我尝试了FindResource和此.Resources[“SingleRole”]但似乎无法使其正常工作。

您应该能够使用
此功能。资源
和演员阵容:

var provider = (ObjectDataProvider)this.Resources["SingleRole"];
SingleRole role = provider.ObjectInstance as SingleRole;
if (role != null)
{
   // Use it here, as it was found properly
}

您应该能够将
此资源与cast一起使用

var provider = (ObjectDataProvider)this.Resources["SingleRole"];
SingleRole role = provider.ObjectInstance as SingleRole;
if (role != null)
{
   // Use it here, as it was found properly
}
这应该行得通-

var a = this.FindResource("SingleRole");
这应该行得通-

var a = this.FindResource("SingleRole");

谢谢你的快速回复。我知道这件事很简单,但为了得到它我浪费了太多的时间。工作完美。感谢您的快速响应。我知道这件事很简单,但为了得到它我浪费了太多的时间。工作完美。