这是一个关于删除逻辑的示例:
<Window x:Class="DeleteCommandStack.MainWindow"
xmlns="http:
xmlns:x="http:
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text=""/>
<Button Content="Delete"
Command="}, Path=DataContext.deleteCommand}"
CommandParameter="}, Path=SelectedItem}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
这里有一个注意点:
ViewModel:
public class ViewModel
{
public ObservableCollection<Model> items { get; set; }
public ICommand deleteCommand { get; set; }
public ViewModel()
{
items = new ObservableCollection<Model>();
items.Add(new Model() { Name = "Name1" });
items.Add(new Model() { Name = "Name2" });
items.Add(new Model() { Name = "Name3" });
items.Add(new Model() { Name = "Name4" });
deleteCommand = new DeleteCommand(this);
}
public void DeleteHandler(object parameter)
{
items.Remove(parameter as Model);
}
}
模型:
public class Model : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
删除命令:
public class DeleteCommand : ICommand
{
private ViewModel _vm;
public DeleteCommand(ViewModel vm)
{
_vm = vm;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_vm.DeleteHandler(parameter);
}
}
还有设置DataContext的代码后台:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
通过将ViewModel引用发送到DeleteCommand,我们能够调用并向其方法发送参数。
我们可以选择直接从命令中删除该项:
public void Execute(object parameter)
{
_vm.items.Remove(parameter as Model);
}
我认为就是这样了,你现在有一个可用的示例。