your xaml should looks like
<ListBox ItemsSource="{Binding List}" SelectedItem="{Binding Item}"/>
and your properties should looks something like
private List<yourClass> list; public List<yourClass> List { get { return list; } set { list = value; RaisPropertyChanged("List"); } } private yourClass item; public yourClass Item { get { return item; } set { item = value; RaisPropertyChanged("Item"); } }
now you only need to set your ViewModle as DataContext and there are many many way's to do this
i'm use a very simple way to do this i create an ResourceDictionary (VMViews.xaml)
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:ProjectName.namespace" xmlns:vw="clr-namespace:ProjectName.namespace" > <DataTemplate DataType="{x:Type vm:YourVMName}"> <vw:YourVName/> </DataTemplate> </ResourceDictionary>
and in my App.xaml
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/Path/VMViews.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
EDIT for SelectedItems
(this code isn't tested)
XAML
<ListBox ItemsSource="{Binding List}" SelectedItem="{Binding Item}" SelectionChanged="ListBox_SelectionChanged"> <ListBox.Resources> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="IsSelected" Value="{Binding IsSelected}" /> </Style> </ListBox.Resources> </ListBox>
now your the yourClass need to implement the IsSelected property
than you can do something like
private yourClass item; public yourClass Item { get { return item; } set { item = value; RaisPropertyChanged("Item"); SelectedItems = List.Where(listItem => listItem.IsSelected).ToList(); } } private List<yourClass> selectedItems; public List<yourClass> SelectedItems { get { return selectedItems; } set { selectedItems = value; RaisPropertyChanged("SelectedItems"); } }
ListBox. Your VM should only expose Model related properties which you can bind to your View, from what I understand.ListBoxControland then don't defineListBoxControlanywhere. If you meant to bind toCurrentListBoxthen most likely what you want to do is use aContentControlinstead:<ConentControl Content="{Binding CurrentListBox}" />, but I'd recommend against it.