【问题标题】:XAML: Accessing arbitrary objects in Application's ResourceDictionaryXAML:访问应用程序的 ResourceDictionary 中的任意对象
【发布时间】:2011-03-14 19:29:13
【问题描述】:

作为 XAML/WPF 新手,我尝试将任意(即非 WPF)对象放入我的应用程序资源中,例如

<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。如果有人能告诉我我做错了什么,我将不胜感激!

【问题讨论】:

  • 代码看起来不错,这是一个完整的例子吗?
  • 您的代码在我的机器上运行良好。确保您没有在实际代码中拼错资源名称
  • 似乎覆盖OnStartup 与绑定到Startup 事件相同。请参阅下面的回复...

标签: wpf xaml code-behind resourcedictionary


【解决方案1】:

好的,资源字典似乎(还没有?)在重写的 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) {

一切正常!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-30
    • 2015-06-14
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多