Reputation: 5343
I want to create listbox dynamically [codebehind c#]. Its datasource is class object.
class sample
{
string filepath;
string id;
string trackName;
}
Needs:
Code:
sample samp=GetBL.GetValue();
ListBox lbTrack = new ListBox();
StackPanel sp = new StackPanel();
lbTrack.ItemSource = samp;
Geetha.
Upvotes: 1
Views: 2841
Reputation: 96920
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.
Upvotes: 2