Search code examples
c#wpfxamlmainwindow

null reference when declaring a class as a window resource


I have problems with accessibility to a class, from the MainWindow code behind.

I have written this class:

namespace WpfApp1.Management
{
    public class BookManagement : INotifyPropertyChanged
    { ...

which is referenced in MainWindow:

<Window
    x:Class="WpfApp1.MainWindow"
    x:Name="mainWindow"
    ...
    xmlns:mangmt="clr-namespace:WpfApp1.Management"

by:

<Window.Resources>
    <mangmt:BookManagement x:Key="bookManagement" />
</Window.Resources>

the fact is that I need to access to bookManagement from MainWindow.cs, and I tried this:

BookManagement bm= Application.Current.Resources["bookManagement"] as BookManagement;
bm.SelectedTab = "summary";

but I get a null reference exception at runtime.

thank you.


Solution

  • It is part of your MainWindow's resources, not part of the application:

    <Window.Resources>
        <mangmt:BookManagement x:Key="bookManagement" />
    </Window.Resources>
    

    Use this to retrieve it instead:

    Application.Current.MainWindow.Resources["bookManagement"]