How to fill ListBox with data entries programatically in Silverlight?
Trying to fill the listbox programatically I have written the following code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
TestDBContext context = new TestDBContext();
context.Load(context.GetTaskQuery());
var taskList = GetTasks();
foreach (var t in taskList)
{
ListBoxTaskItems.Items.Add(t);
}
}
private List<TaskItem> GetTasks()
{
var tasks = from t in context.Tasks
select new TaskItem(t);
return tasks.ToList();
}
The problem is that the code above alway returns an empty ListBox. Does any开发者_JAVA百科one know how to modify the existing code or another way to programatically fill the listbox with the data entries?
Edit #1: While debugging I've noticed that GetTasks() method is executed before context.GetTaskQuery() and I gues this is the reason for an empty ListBox. Nevertheless I don't know how to fix the code in order to populate the ListBox.
Thank you!
Somebody posted another solution, then for whatever reason deleted it, but that might work better. I just tried it in some code I'm working on and found it was faster:
Binding bind = new Binding();
bind.Source = GetTasks();
ListBoxTaskItems.SetBinding(ListBox.ItemsSourceProperty, bind);
(Substitute this for the foreach statement).
I'd try it like this inside your foreach statement:
ListBoxItem listBoxItem = new ListBoxItem();
listBoxItem.Content = t;
ListBoxTaskItems.Items.Add(listBoxItem);
I do something similar and it works when adding Grids to a ListBox, so as long as a TaskItem is something acceptable as Content that should do it.
精彩评论