1

我有一个在 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>

我试图在代码中获取对该对象的引用:

    private void button1_Click_1(object sender, RoutedEventArgs e)
    {
        SingleRole role = ????;
    }

我怎样才能做到这一点?我试过 FindResource 和 this.Resources["SingleRole"] 但我似乎无法让它工作。

4

2 回答 2

1

您应该可以使用this.Resources演员表:

var provider = (ObjectDataProvider)this.Resources["SingleRole"];
SingleRole role = provider.ObjectInstance as SingleRole;
if (role != null)
{
   // Use it here, as it was found properly
}
于 2012-10-24T16:55:24.053 回答
0

这应该工作 -

var a = this.FindResource("SingleRole");
于 2012-10-24T16:55:53.773 回答