我有一个ListBox
,其SelectionMode
属性设置为Extended
,以允许在ListBox内进行多次选择。 ListBox绑定到ObservableCollection
。我想要做的是,当我按下删除键时,列表框中的所选项目将从ObservableCollection中删除。我知道如何设置键绑定并使用删除键的命令,但我不确定如何从ListBox中获取多个选项。
这是列表框:
<ListBox ItemsSource="{Binding XtfPaths}"
SelectionMode="Extended"/>
这里是viewmodel:
private ObservableCollection<String> _xtfPaths = new ObservableCollection<String>();
public ObservableCollection<String> XtfPaths
{
get { return _xtfPaths; }
set
{
if (null != value)
{
_xtfPaths = value;
OnPropertyChanged("XtfPaths");
}
}
}
答案 0 :(得分:1)
试试这个
<Grid>
<StackPanel>
<ListBox x:Name="list" Height="200"
SelectionMode="Extended"
ItemsSource="{Binding SampleItems}" >
</ListBox>
<Button Content="Remove" Command="{Binding DeleteCommand}"
CommandParameter="{Binding ElementName=list, Path=SelectedItems}">
</Button>
</StackPanel>
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel1();
}
}
public class MainViewModel1
{
private ObservableCollection<string> m_items;
public ObservableCollection<string> SampleItems
{
get { return m_items; }
set { m_items = value; }
}
public ICommand DeleteCommand { get; private set; }
public MainViewModel1()
{
DeleteCommand = new RelayCommand<object>(Delete, CanDelete);
var items = new ObservableCollection<string>();
var today = DateTime.Now;
for (int i = 1; i <= 10; i++)
{
items.Add("Test"+i);
}
SampleItems = items;
}
private void Delete(object obj)
{
var items = new ObservableCollection<string>();
foreach (var item in (IList)obj)
{
items.Add((string)item);
}
foreach (var item in items)
{
m_items.Remove(item);
}
}
private bool CanDelete(object obj)
{
return true;
}
}