【问题标题】:null reference when declaring a class as a window resource将类声明为窗口资源时的空引用
【发布时间】:2018-11-19 18:33:17
【问题描述】:

我无法从后面的 MainWindow 代码中访问一个类。

我已经写了这门课:

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

MainWindow 中引用的:

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

作者:

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

事实是我需要从 MainWindow.cs 访问 bookManagement,我尝试了这个:

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

但我在运行时遇到空引用异常。

谢谢。

【问题讨论】:

    标签: c# wpf xaml mainwindow


    【解决方案1】:

    它是您MainWindow 资源的一部分,而不是应用程序的一部分:

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

    使用它来检索它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2022-01-16
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多