0

The following code is in a WPF project using NavigationWindow. The code behind has several override methods. In the override below 'favoritesItem' must be accessed. 'favoritesItem' is located in a separate .XAML file. Clearly I am not accessing it properly. This is the override:

Protected Overrides Sub OnClosed(e As EventArgs)
  MyBase.OnClosed(e)
  ' Persist the list of favorites
  Dim f As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly()
  Using stream As New IsolatedStorageFileStream("myFile", FileMode.Create, f)
    Using writer As New StreamWriter(stream)
      For Each item As TreeViewItem In DirectCast(System.Windows.Application.Current.Properties("favoritesItem"), TreeViewItem).Items
        writer.WriteLine(TryCast(item.Tag, String))
      Next
    End Using
  End Using
End Sub

This error is:

Object reference not set to an instance of an object

What is the proper method to access a XAML element [edited] in a different file?

Alan
  • 1,587
  • 3
  • 23
  • 43
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Trevor Feb 15 '17 at 23:18
  • I understand the object is returning a NullReferenceException, but isn't that because I'm not accessing the Property correctly? The Cast doesn't have anything to return because the Property isn't actually accessed, yes? I assume if I get the Property reference corrected, then I'll receive the data from the TreeView. What I don't understand is how to access that Property. – Alan Feb 15 '17 at 23:27

1 Answers1

1

What are you trying to do here? The code you posted has got nothing to do with accessing "XAML objects in another file". The Application.Properties property is just a dictionary for sharing data, in a thread-safe fashion between different parts of your application. It is very rarely used in my experience - in fact I have never seen it used. You are getting a null exception because you probably haven't added the 'favoritesItem' to the dictionary first.

If you want to access a named XAML element from another class you will need to expose it via a public property. (Named XAML elements create private member fields in their defining class).

Jack Ukleja
  • 13,061
  • 11
  • 72
  • 113
  • You identified my issue. I'm following a project and didn't catch that the property had to be manually loaded into the dictionary. My phrasing regarding 'objects in another file' was probably poorly written. I actually was trying to access the data of an element (TreeViewItems) from a different page. So would it have been better to refer to it as an element in the title and post? BTW, how do I expose a named XAML element publicly? – Alan Feb 16 '17 at 02:46
  • As it says in the answer > "If you want to access a named XAML element from another class you will need to expose it via a public property" – Jack Ukleja Feb 16 '17 at 03:27