2

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
}

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

The benefit is hidden in // other initialize for item object, which I comment out. There are too much code in there. :(
I still think that it is better to set the ItemsSource of the ListBox to the list and then just use your datatemplate from the XAML. Then it would be automatically use the correct DataContext for each Item an will the Name property be read
I tried as you said, it took me some time. I have to convert lots of code into xmal, which is too hard to understand for other people.
0

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

1 Comment

After double check the Output, I found out where I was wrong. I have update my question. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.