Question

here's the problem: In my WPF application I used to load/parse my .xaml files using XamlReader.Load Method to open a window in my application.

Codefragment of my function which return the window:

Dim win As New Window()
Dim myObject As Object

Dim xml As XmlReader = XmlReader.Create("mysample.xaml")
myObject = System.Windows.Markup.XamlReader.Load(xml)
win = CType(myObject, Window)
Return win

I use this to display all my different windows the user wants to see.

I open the window with win.Show and close it, when user switch to another window with win.Close. It works well!

Now to increase the performance I plan to do all the XAMLReader.Load at Application Start and store the information into a Dictionary:

Private Shared windict As Dictionary(Of String, Object)

Public Shared Sub ConvertXAMLToWindow(ByVal formName As String)
      windict = New Dictionary(Of String, Object)
      Dim myObject As Object
      Dim xml As XmlReader = XmlReader.Create(formName)
      myObject = System.Windows.Markup.XamlReader.Load(xml)
      windict.Add(formName, myObject)
End Sub

Then I want to use that information when calling windows:

If windict.ContainsKey(formName) Then
 Dim win As New Window()
 Dim myObject As Object

 myObject = windict(formName)
 win = CType(myObject, Window)
 Return win
End If

Now This works well, but when I use win.Close to close my window I get an error when trying to open it again with win.Show, although I create an new instance of Window?

System.InvalidOperationException Cannot set Visibility or call Show, ShowDialog... after a Window has closed.

But it works when I don't use the Dictionary Method but the XAMLReader.Load directly - any ideas whats going on ? Somehow the window I get by returning XamlReader.Load seems different than the stored information from the dict?? Am I missing somehting? Thanks in advance!

Was it helpful?

Solution

You could use Hide() instead of Close()

Hide hides the Form, so instead of disposing of the form (and its controls) you make it invisible. Show will make it visible again.

Be careful though, the form in the dictionary will still hold the state from the previous time it was used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top