【发布时间】: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