Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

wpf

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?

like image 858
Jim C Avatar asked Jun 12 '14 19:06

Jim C


1 Answers

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

  • WPF: Cannot find resource defined in the App.xaml file
  • Application.Resources Not Loaded if Doesn't Have StartupURI Property
  • Bug: Single Entry Ignored

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">
like image 166
dkozl Avatar answered Sep 28 '22 02:09

dkozl