0
votes

I'm just starting with wpf/vmmv. I've seen examples of binding collections to list boxes. Example: in xaml , in code-behind (e.g. Page) "DataContext = collection.. ".

My view model has more properties than just a single collection that need to be bound to a view. Therefore I'd like to set the view model as DataContext for the view and then, in xaml, bind the view model's collection to a ListBox. Assuming that my view model is set as DataContext and it has a property called 'Customers', what is the correct way of binding the property to a ListBox in xaml? I tried but it does not work.

Thanks.

2

2 Answers

2
votes

Do you mean 'how do you bind a collection to a 'ListBox'? You would do that like this:

<ListBox ItemsSource="{Binding Customers}" />

Or this:

<ListBox ItemsSource="{Binding Path=Customers}" />

If you want to bind the internal values of each instance of the Customer class, you would do something like this:

<ListBox ItemsSource="{Binding Customers}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}" />
            <TextBlock Text="{Binding Age}" />
            <TextBlock Text="{Binding EyeColour}" />
        </DataTemplate>
    </ListBox.ItemTemplate>        
</ListBox>
0
votes

I guess you want to display the property "Customers", what you have to do is define ItemTemplate of ListBox, define DataTemplate inside ItemTemplate, and binding Customers to a control, just like below:

<ListBox ItemsSource="{Binding}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Customers}"/>
            ......something else you want display
        </DataTemplate>
    </ListBox.ItemTemplate>

</ListBox>