3

I have a UWP app written in C#, where I need to open a second window.

Inside this second window, there is an element that I need to toggle the visibility of (in some cases).

Please find an MVCE here: https://github.com/cghersi/UWPExamples/tree/master/AppWindowAndVisibility

If you look into it, you will see an element m_searchGrid which we can change the visibility (using method SwitchSearchBarVisibility())

To open a new window, I use the primitives AppWindow.TryCreateAsync and ElementCompositionPreview.SetAppWindowContent.

Now, the following procedure results in an Exception when calling ElementCompositionPreview.SetAppWindowContent:

  1. Open a new window (in the app, click on the button "Open AppWindow")
  2. Change the visibility of an element in the newly opened window (in the app, in the new window that is opened, click on the button "Show/hide search bar")
  3. Close the second window
  4. Reopen again another window (in the app, re-click on the button "Open AppWindow")

From a code perspective, at step 4 I can see that the method ElementCompositionPreview.SetAppWindowContent throws an Exception (see line 108 of MainPage.xaml.cs, in the method ShowAsync()).

Do you have any clue on what could be the cause?

Maybe I should configure the window or the element in different ways?

Thanks!!

Cristiano Ghersi
  • 1,944
  • 1
  • 20
  • 46

1 Answers1

1

UWP Cannot open an external window after changing visibility of an inner element

The problem is m_wrapperCanvas was used by previous m_appWindow, it was not released even you called m_appWindow = null.

For solved this problem we suggest set m_wrapperCanvas = null, and re-new the m_wrapperCanvas before ElementCompositionPreview.SetAppWindowContent

private void AppWindow_OnClosed(AppWindow sender, AppWindowClosedEventArgs args)
{
    m_appWindow.Closed -= AppWindow_OnClosed;
    m_appWindow = null;
    m_wrapperCanvas = null;
}

..........

try
{
    Init();
    ElementCompositionPreview.SetAppWindowContent(m_appWindow, m_wrapperCanvas);
}
Nico Zhu
  • 32,367
  • 2
  • 15
  • 36
  • 1
    Thanks Nico, it is not ideal because we wish to re-use the content inside m_wrapperCanvas but at least we have a workable solution! – Cristiano Ghersi Nov 02 '21 at 16:11