Jim C
Jim C

Reputation: 4648

Can't retrieve WPF application resource if there is only one

Is ths a bug in my code or in WFP? Using VisualStudio 2013, targeting .NET 4.5.1.

<Application x:Class="WPFDemo.MyApp"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:vm="clr-namespace:WPFDemo.ViewModels">

    <Application.Resources>
        <vm:TestClass x:Key="tc" />
    </Application.Resources>
</Application>

   public partial class MyApp : Application
   {  
      protected override void OnStartup(StartupEventArgs e)
      {
         base.OnStartup(e);
         var mainWindow = new MainWindow();
         mainWindow.Show();
      }
   }

   public partial class MainWindow
   {
      public MainWindow()
      {
         InitializeComponent();
         object o = Application.Current.Resources["tc"];
      }
   }

Problem: o is null.

If I add at least one other resource of any type:

<Application.Resources>
    <vm:TestClass x:Key="tc" />
    <vm:TestClass2 x:Key="tc2" />
</Application.Resources>

and make no other changes anywhere, o comes back as an instance of TestClass.

Huh?

Upvotes: 6

Views: 2754

Answers (2)

琥珀松
琥珀松

Reputation: 31

Well, a better way to solve this problem is add "InitializeComponent()" into the constructor of App class, just like:

    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            //other codes below
        }
}

Upvotes: 3

dkozl
dkozl

Reputation: 33364

I've found few references to bug when Application.Resources don't load when StartupURI is not defined

and there seem to be 3 workarounds to this problem (4 including creating dummy resource)

Define dictionary

<Application.Resources>  
    <ResourceDisctionary>
        <ResourceDictionary.MergedDictionaries/>
        <vm:TestClass x:Key="tc" />
    </ResourceDisctionary>
</Application.Resources>

but it seems strange as it requires empty ResourceDictionary.MergedDictionaries tag

Don't override OnStartup method but use Startup event instead

<Application ... Startup="Application_Startup">

and in code

private void Application_Startup(object sender, StartupEventArgs e)
{
    var mainWindow = new MainWindow();
    mainWindow.Show();
}

Give your Application a name

<Application ... x:Name="myApplication">

Upvotes: 11

Related Questions