Reputation: 742
I am getting an exception "Object reference not set to an instance of an object." on the "songs.DataContext =" line. If I add songs = new ListView(); before it my listview is empty even though the list of audiofiles is not
XAML:
<ListView Height="Auto" HorizontalAlignment="Center" ItemsSource="{Binding}"
VerticalAlignment="Center" Name="songList" Width="Auto" MinHeight="300" MinWidth="600">
<ListView.View>
<GridView>
<GridViewColumn Width="Auto" Header="Title" DisplayMemberBinding="{Binding Path=Title}" />
<GridViewColumn Width="Auto" Header="Artist" DisplayMemberBinding="{Binding Path=Artist}" />
<GridViewColumn Width="Auto" Header="Album" />
<GridViewColumn Width="Auto" Header="Length" />
</GridView>
</ListView.View>
</ListView>
C#
public struct AudioFile
{
public String Artist;
public String Title;
public String Album;
public String fileLocation;
public String Length;
}
//...
private List<AudioFile> songs = new List<AudioFile>();
//code that adds to array
songList.DataContext = songs;
Upvotes: 1
Views: 1103
Reputation: 81233
Are you writing this code -
//...
private List<AudioFile> songs = new List<AudioFile>();
//code that adds to array
songList.DataContext = songs;
before IniitializeComponent() method is called for a view?? Can you provide a bit more of insight regarding your code placement that will help in understanding the situation better.
And just a suggestion, not related though. I would say use class instead of structure objects because WPF data binding considers only properties, not fields. Definitely, this is not a cause of an error though.
Upvotes: 0
Reputation: 18031
I suspect your code to be in the constructor, in a place where songList is not yet created.
//...
private List<AudioFile> songs = new List<AudioFile>();
//code that adds to array
songList.DataContext = songs;
Try to move it in the Loaded event instead.
Upvotes: 1
Reputation: 39916
I think you may be trying to set songList.ItemsSource = list in your constructor and obviously the object is not built yet.
In your UI classes, best place to initialize will be only in Loaded event or after InitializeComponent method.
Even better approach will be to use MVVM.
Upvotes: 0
Reputation: 184296
Your songs
are clearly instatiated, but what about the songList
?
Upvotes: 0