C# 订阅事件时无法创建Usercontrol的实例

C# 订阅事件时无法创建Usercontrol的实例,c#,wpf,visual-studio,xaml,C#,Wpf,Visual Studio,Xaml,还有其他关于这个主题的帖子,但我没有找到任何与我的具体问题相关的帖子 在Visual Studio 2017中,我遇到了这样一种情况:XAML设计器提示错误,尽管似乎没有出现任何奇怪的情况 基本上,为了重现这个问题,考虑这两个文件, main window.xaml <Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xm

还有其他关于这个主题的帖子,但我没有找到任何与我的具体问题相关的帖子

在Visual Studio 2017中,我遇到了这样一种情况:XAML设计器提示错误,尽管似乎没有出现任何奇怪的情况

基本上,为了重现这个问题,考虑这两个文件,

main window.xaml

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TabControl Background="White">
            <TabItem Header="TEST" Width="60">
                <local:UserControl1/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>
这很奇怪,因为启动应用程序时,一切都正常工作。通过创建一个新的WPF应用程序并创建如上所示的相同模式,可以很容易地复制

注意

我试图删除订阅

App.Current.MainWindow.Closing += window_Closing;

它消除了错误。所以,这是原因,但为什么呢?

App.Current
在设计模式下将为空

您可以检查IsInDesignMode以防止运行此代码。像

public UserControl1()
{
    InitializeComponent();
    if(!DesignerProperties.GetIsInDesignMode(this))
        App.Current.MainWindow.Closing += window_Closing;
}

相关post in.

在设计模式下,它将尝试运行用户控件的构造函数,并且由于主窗口尚未设置,它将在事件订阅期间引发异常。在订阅事件之前,您可以轻松检查是否处于设计模式,如下所示:

if (!DesignerProperties.GetIsInDesignMode(this))
    App.Current.MainWindow.Closing += window_Closing;

哇,真是个好球。谢谢。
public UserControl1()
{
    InitializeComponent();
    if(!DesignerProperties.GetIsInDesignMode(this))
        App.Current.MainWindow.Closing += window_Closing;
}
if (!DesignerProperties.GetIsInDesignMode(this))
    App.Current.MainWindow.Closing += window_Closing;