2011-03-14 52 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) { 

一切正常!