0

I try to bind XAML ListBoxItem using Code but doesn't seem work

In my XAML:

<Window.Resources>
    <local:FooList x:Key="FooListItem" />
</Window.Resources>

< ListBox x:Name="ListBox1" ItemsSource="{Binding Source={StaticResource FooListItem}}" />

In my code:

public class FooList
{
    add some items; // I tried variation of that but didn't get it to work
}

Any tips?

KMC
  • 19,548
  • 58
  • 164
  • 253

2 Answers2

1

You don't create ListBoxItem from code.

You just provide a ListBox with collection of your CLR class objects, provide an ItemTemplate and it implicitly wraps an ItemTemplate inside a ListBoxItem.

Example:

public class FooList
{
    public ObservableCollection<String> Items { get; set; }

    public FooList()
    {
        Items = new ObservableCollection<String>();
    }
}

XAML:

<ListBox x:Name="ListBox1" ItemsSource="{Binding Path=Items, Source={StaticResource FooListItem}}" />
decyclone
  • 30,394
  • 6
  • 63
  • 80
  • I can do it in XAML. But I cannot do this in code? How could you provide ItemTemplate in code? – KMC Dec 15 '10 at 10:14
  • Thanks for more detail. But I need to do that without observableCollection. I am following this tutorial: http://msdn.microsoft.com/en-us/library/ms742521.aspx#without_a_datatemplate and they were able to bind ItemsSource but didn't provide any explanation... – KMC Dec 15 '10 at 11:02
  • That is because `Tasks` type in that example is a `Collection` itself. – decyclone Dec 15 '10 at 11:14
  • I guess I'm not making my question clear, please see this question http://stackoverflow.com/questions/4451171 – KMC Dec 15 '10 at 15:03
1

Programmatically binding List to ListBox

Listbox with custom drawn data bound objects

Data Binding in WPF

Windows Presentation Foundation Data Binding: Part 1

Community
  • 1
  • 1
abmv
  • 7,042
  • 17
  • 62
  • 100
  • I'm actually following a tutorial http://msdn.microsoft.com/en-us/library/ms742521.aspx#without_a_datatemplate but it doesn't show any C# code and I can't figure it out. Your tutorial link also doesn't show any code. – KMC Dec 15 '10 at 10:15
  • check http://stackoverflow.com/questions/449410/programmatically-binding-list-to-listbox – abmv Dec 15 '10 at 10:22