开发者

How to create Listbox dynamically wpf

I want to create listbox dynamically [codebehind c#]. Its datasource is class object.

class sample
{
  string filepath;
  string id;
  string trackName;
}

Needs:

  1. Display trackName as 开发者_JAVA技巧listbox item in the listbox [dynamically].

Code:

sample samp=GetBL.GetValue();
ListBox lbTrack = new ListBox();
StackPanel sp = new StackPanel();
lbTrack.ItemSource = samp;

Geetha.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜