All is in the title, I want to do something like :
<ListBox AssignTo="{Binding ListBoxControl}" ...
Then in my ViewModel having a property like this :
public ListBox CurrentListBox
{
get;
set;
}
What I want is to easely retrieve the selected items
Could I do that?
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>
(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");
}
}
Another person had similar issues while trying to learn...
Take a look at this answer to help
Your property is exposed via public getter/setter (although setter can be private to your data context object).
Then, the property of the listbox "Items" will get "bound" to your exposed property.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.