I have a ListBox containing filenames. Now I need to get array of selected items from this ListBox. I found a few answers here, but none of them worked for me. I\'am using C
You can use this code for MVVM Pattern
XAML
<ListBox x:Name="DeleteHistoryListBoxItem" SelectedItem="{Binding Path=DeleteHistorySelectedItem,UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding DeleteHistoryListBox, NotifyOnSourceUpdated=True}" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Item}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
ViewModel
private ObservableCollection<HistoryItems> deleteHistoryListBox = new ObservableCollection<HistoryItems>();
public ObservableCollection<HistoryItems> DeleteHistoryListBox
{
get
{
return deleteHistoryListBox;
}
set
{
deleteHistoryListBox = value;
this.RaisePropertyChanged("DeleteHistoryListBox");
}
}
private HistoryItems deleteHistorySelectedItem;
public HistoryItems DeleteHistorySelectedItem
{
get
{
return deleteHistorySelectedItem;
}
set
{
var selectedItems = DeleteHistoryListBox.Where(x => x.IsSelected).Count();
this.RaisePropertyChanged("DeleteHistorySelectedItem");
}
}
Class
public class HistoryItems : INotifyPropertyChanged
{
private string item;
public string Item
{
get { return item; }
set
{
item = value;
this.RaisePropertyChanged("Item");
}
}
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set
{
isSelected = value;
this.RaisePropertyChanged("IsSelected");
}
}
}
You can add SelectionChanged event handler in code-behind, and update property for selected items in the ViewModel from there.
XAML:
<ListBox x:Name="DeleteHistoryListBox" SelectedItem="{Binding Path=DeleteHistorySelectedItem}"
ItemsSource="{Binding DeleteHistoryListBox, NotifyOnSourceUpdated=True}"
SelectionMode="Multiple" SelectionChanged="DeleteHistoryListBox_SelectionChanged">
</ListBox>
DeleteHistoryView.xaml.cs
private void DeleteHistoryListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DeleteHistoryViewModel vm = (DeleteHistoryViewModel)DataContext;
foreach (string item in e.AddedItems)
{
vm.DeleteHistorySelectedItem.Add(item);
}
foreach (string item in e.RemovedItems)
{
vm.DeleteHistorySelectedItem.Remove(item);
}
}