Есть модель в которой есть список файлов. Этот список прибинден к ListBox
.
Как получить список выбранных строк, если установлен режим SelectionMode="Extended"
?
1 ответ
Не я первый столкнулся с этой проблемой.
Вот решение через CustomListBox: https://stackoverflow.com/questions/22868445/wpf-binding-selecteditems-in-mvvm
Создаем наследника от ListBox
и добавляем DependencyProperty
public class CustomListBox: ListBox
{
public CustomListBox()
{
this.SelectionChanged += CustomListBox_SelectionChanged;
}
private void CustomListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.SelectedItemsList = this.SelectedItems;
}
public IList SelectedItemsList
{
get { return (IList)GetValue(SelectedItemsListProperty); }
set { SetValue(SelectedItemsListProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedItemsList. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedItemsListProperty =
DependencyProperty.Register("SelectedItemsList", typeof(IList), typeof(CustomListBox), new PropertyMetadata(null));
}
XAML:
<Windows ...
xmlns:customObjects ="clr-namespace:Preparation.CustomObjects"/>
<customObjects:CustomListBox x:Name="listBox"
SelectionMode="Extended"
ItemsSource="{Binding Planshets}"
SelectedItemsList="{Binding SelectedPlanshets, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
ViewModel:
private IList _selectedPlanshets = new ArrayList();
public IList SelectedPlanshets
{
get { return _selectedPlanshets; }
set
{
_selectedPlanshets = value;
RaisePropertyChanged("SelectedPlanshets");
}
}
Теперь в нашей модели доступно свойство ViewModel.SelectedPlanshet
SelectedItems="{Binding Selecteditems}"
?SelectedItems
уListBox
, есть толькоSelectedItem
...