2011-03-14 63 views
0

是一个XAML/WPF新手访问任意对象,我试图把任意的(即非WPF)对象到我的应用程序资源,如XAML:在应用程序的资源字典

<Application x:Class="MyApp.App" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:a="clr-namespace:MyApp" 
     > 
    <Application.Resources> 
    <a:MyClass x:Key="Model"/> 
    </Application.Resources> 
</Application> 

,并从我的代码 - 访问它背后使用文件

public partial class App : Application 
{ 
    protected override void OnStartup(StartupEventArgs e) { 
    base.OnStartup(e); 
    var obj = (MyClass)this.FindResource("Model"); 
    obj.DoSomething(); 
    } 
} 

FindResource了我一个ResourceReferenceKeyNotFoundException。如果有人能告诉我我做错了什么,我会非常感激!

+0

代码看起来不错,这是一个完整的例子吗? – devdigital 2011-03-14 10:55:21

+0

您的代码在我的机器上正常工作。确保你没有在你的实际代码中拼写错误的资源名称 – 2011-03-14 11:13:08

+0

看起来,重写'OnStartup'与绑定到'Startup'事件*不同。在下面看到我的回复... – MartinStettner 2011-03-14 11:30:06

回答

2

好吧,似乎资源字典不是(还没有?)在重写的OnStartup方法中初始化,但在Startup事件处理程序中可用。

当我使用Startup事件而不是压倒一切OnStartup像:

<Application x:Class="MyApp.App" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:a="clr-namespace:MyApp" 
    Startup="Application_Startup" 
     > 

private void Application_Startup(object sender, StartupEventArgs e) { 

一切正常!

相关问题