Chuanyu Wang
Chuanyu Wang

Reputation: 47

How to create ListBoxItem within behind code

For some reason I have to initialize the ListBox items in behind code, the reason is too complication to tell.

The LoadFamily() is called during WPF UserControl show up.

public void LoadFamily()
{
    DataTemplate listItemTemplate = this.FindResource("ManDataTemplate") as DataTemplate;

    foreach (Person man in family)
    {
        ListBoxItem item = new ListBoxItem();

        item.DataContext = man;
        item.ContentTemplate = listItemTemplate;
        // other initialize for item object
        this.ActivityList.Items.Add(item);
    }
}

In my xmal file, I define a DataTemplate.

<DataTemplate x:Key="ManDataTemplate" DataType="{x:Type local:Person}">
    <TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>

But the ListBox only contains empty text block, the person's Name doesn't not display. I don't know why, maybe the data binding is wrong, but how to do it in behind code.

Thanks for your any help! (WPF 3.5 or 4.0)

/////////////////////////////////////////////////////////////

Thanks for all your help. I found where I was wrong. I should not add ListBoxItem into ActivityList.Items, one is UIElement, the other is >DataCollection. They are two different thing.

I should modify the code as follow:

foreach (Person man in family)
{
    this.ActivityList.Items.Add(man);
    ListBoxItem item = this.ActivityList.ItemContainerGenerator.ContainerFromItem(man) as ListBoxItem;
    item.ContentTemplate = listItemTemplate;
    // other initialize for item object
}

Upvotes: 2

Views: 1670

Answers (2)

Prince Ashitaka
Prince Ashitaka

Reputation: 8773

There could be binding error. That's the reason why the textblock is empty. Check the Output window of VisualStudio, it will display the binding errors if exist.

HTH

Upvotes: 0

Wouter Janssens
Wouter Janssens

Reputation: 1613

I don't see the benefit of creating the listboxitems manually. Just set the ItemsSource of the Listbox to the list of person (family).

Upvotes: 1

Related Questions