Create a class that exposes an ObservableCollection<sample>
as a property named, say, Samples
. Create an instance of this class, populate its collection, and add the class to the window's resource dictionary, with a key of, let's say, Data
. Override ToString()
in the sample
class to make it return what you want to appear in the ListBox
.
Then do this:
<ListBox ItemsSource="{StaticResource Data, Path=Samples}"/>
Without overriding ToString()
, you can specify a display binding:
<ListBox ItemSource="{StaticResource Data, Path=Samples}"
DisplayMemberBinding="{Binding Path=trackName"/>
Note that trackName
must be a property, not a field.
You'll notice that I'm not programmatically creating WPF controls, and am instead using data binding to do it for me. This is an essential, fundamental concept of WPF application development.