来自Window.Resources中对象的FindResource

时间:2012-10-24 16:54:06

标签: 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" 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”],但我似乎无法让它工作。

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

这应该有效 -

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