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?
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With