Manuel
Manuel

Reputation: 11469

Window is not recognizing an application resource

To reproduce the error:

Create a new MVVM-Light WPF application.

Copy MainWindow.xaml to MainWindow2.xaml Rename MainWindow2's class name to MainWindow2 (and the constructor)

Rename MainWindow2 window class attribute to "x:Class="MvvmLight2.MainWindow2"

Remove StartupUri from App.xaml

Add the following to App:

protected override void OnStartup(StartupEventArgs e)
{
    new MainWindow().Show();
    new MainWindow2().Show();
}

Run the application and get error:

Cannot find resource named '{Locator}'. Resource names are case sensitive.  Error at object 'System.Windows.Data.Binding' in markup file 'MvvmLight2;component/mainwindow.xaml' Line 10 Position 9.

To resolve the error: Remove DataContext="{Binding Main, Source={StaticResource Locator}}" from both windows.

Add the following line to both windows' constructors:

DataContext = new ViewModelLocator().Main;

The application now runs.

The question is why doesn't it recognize the Locator even though it's defined as an application resource?

Update:

I just noticed that I can add the same resource on both xaml and code without any visible side effects. The question now becomes, is there a problem with this? Does it create a duplicate resource or it doesn't because they have the same key? More than just hacking it, I'm trying to understand what's going on.

Upvotes: 3

Views: 1840

Answers (1)

Michal Ciechan
Michal Ciechan

Reputation: 13888

Managed to fix this by adding InitializeComponent() inside Application.Startup event handler:

App.xaml

<Application x:Class="SomeNamespace.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="Application_Startup"> <!-- Important to use Startup -->

App.xaml.cs

public partial class App : Application
{
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        InitializeComponent(); // <-- Important to set this!

        var window = new MainWindow();

        window.Show();
    }
}

Upvotes: 4

Related Questions