在 Windows 切换用户或远程桌面登录时调用的 WPF View 构造函数

Lum*_*umo 5 .net wpf user-interface

我有一个 WPF 窗口,其中包含ContentControl使用DataTemplate在 Windows 资源中定义的a :

<Window (...)>
    <Control.Resources>
        <DataTemplate DataType="{x:Type local:MainVM}">
            <local:MainView />
        </DataTemplate>
    </Control.Resources>

    <ContentControl Content="{Binding}" />

    <!--<local:MainView /> This Works as expected -->
</Window>
Run Code Online (Sandbox Code Playgroud)

为了测试,这MainView是一个没有内容的普通 wpf 用户控件。

在我的 MainWindow 构造函数中,我设置了 datacontext 一次:

public MainWindow()
{
     InitializeComponent();
     DataContext = new MainVM();
}
Run Code Online (Sandbox Code Playgroud)

通常,MainView如果我从不更改DataContext窗口的,我希望构造函数只被调用一次。

但是,每次我使用远程桌面登录我的机器时,或者当我按下“切换用户”并重新登录时,都会调用它:

public MainView()
{
    InitializeComponent(); // <--- this is called upon loggin on
}
Run Code Online (Sandbox Code Playgroud)
  • 既不调用窗口DataContextChanged事件也不MainView.Unloaded调用事件。

  • 这仅发生在我的 Windows 10 Pro 64 位 v1511 机器上,而不发生在 Windows 7 PC 上。

  • 它也只有在我使用 时才会发生ContentControl,而不是在我直接创建 MainView 时发生。

  • 如果屏幕只是锁定,则不会发生。

有谁知道为什么会发生这种情况或我如何防止这种情况发生?

我在 StackOverflow 上发现了其他可能解决相同问题的帖子:

WPF:防止 RDP(断开)连接后卸载和加载

使用远程桌面连接 (RDP) 连接到 pc 时,WPF 重新调用构造函数