所以我有一个 ListView ,它的 itemsSource 属性绑定(bind)到一个 ObservableCollection,放置在 View 模型上。还有一个按钮打开 View
如何使按钮从 observableCollection 中删除在 ListView 中选择的项目?
最佳答案
只是添加另一种方式来做到这一点:
<ListView ItemsSource="{Binding MyList}"
SelectedItem="{Binding SelectedItem}"/>
<Button Command="{Binding DeleteCommand}"/>
在您的 ViewModel 中,您有一个名为
SelectedItem
的属性。每次更改 ListView
中的选择时都会更新。 .现在您可以在
ViewModel
中处理删除操作了容易地:internal class ViewModel
{
public ViewModel()
{
this.DeleteCommand = new RelayCommand(() => this.Delete());
}
public void Delete()
{
this.MyList.Remove(this.SelectedItem);
}
}
前往 HERE有关
RelayCommand
的更多信息
关于c# - 如何从列表中删除?面向 MVVM 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13217470/