Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a collection class as a static resource in silverlight

I have a simple class named Customer with 2 properties.
public Name {get;set;}
public LastName {get;set}

Then I made a collection class named CustomerList with only one public property named Customers

public class CustomerList
{
    public List<Customer> Customers { get; set; }

    public CustomerList()
    {
        Customers = new List<Customer>();
        Customers.Add(new Customer() { Name = "Foo", LastName = "Bar" });
        Customers.Add(new Customer() { Name = "Foo1", LastName = "Bar1" });
    }
}

Now I want to use this class as a static resouce in XAML.

  <UserControl.Resources> 
  <customers:CustomerList x:Key="CustomersKey">
  </UserControl.Resources>

and then use it in a ListBox

 <ListBox x:Name="lvTemplate" ItemsSource="{Binding Source={StaticResource CustomersKey}}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBox Text="{Binding Name}"/>
                    <TextBox Text="{Binding LastName}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

if I set the ItemsSource in code behide, after instantiating the class, all work fine. If I try to set it from XAML and the static resource Nothing happens. not even if I use the {Binding Path=Customer.Name} or {Binding Path=Name}.

Clearly I miss something...

like image 451
Panagiotis Lefas Avatar asked Feb 28 '11 19:02

Panagiotis Lefas


1 Answers

Since the CustomerList isn't actually the list of items (does not implement IEnumerable), you need to specify what property inside the object you want to use as ItemsSource.

<ListBox ItemsSource="{Binding Path=Customers, Source={StaticResource CustomersKey}}">
like image 187
foson Avatar answered Nov 14 '22 08:11

foson