【发布时间】:2020-10-03 19:42:27
【问题描述】:
我有一个带有DataGrid、菜单和按钮的 WPF 应用程序。当DataGrid 中的行被选中时,按钮和菜单项被激活,以允许从数据库中删除数据。
此主窗口的部分 XAML:
<Button ToolTip="Delete Record" Command="{Binding DeleteCommand}" Name="button_delete" IsEnabled="False"/>
<MenuItem>
<MenuItem Header="Delete" IsEnabled="False" Name="menuItem_delete" Command="{Binding DeleteCommand}"/>
</MenuItem>
<DataGrid Name="BooksDataGrid" ItemsSource="{Binding BooksList}" SelectionChanged="dataGrid_selectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Header="Title" Binding="{Binding title_long}"/>
<DataGridTextColumn Header="ISBN" Binding="{Binding isbn}"/>
</DataGrid.Columns>
</DataGrid>
DeleteCommand 将在上述主窗口的DataContext 类中定义。该类部分代码如下:
sealed class BookViewModel
{
public ObservableCollection<IBook> Books { get; private set; }
// load data command code
// delete record command code
// ...
public void deleteAction(IEnumerable<string> isbnList)
{
// delete data from database
// this already works
}
}
已经实现了从数据库加载数据的命令。这与以下问题的答案非常相似:How to bind WPF button to a command in ViewModelBase?
要达到的目标:
- 当
DataGrid中的项目被选中时,如果一个或多个项目被选中,则删除命令的 UI 元素将被激活。这已经通过以下事件处理程序在主窗口的代码隐藏中实现:
private void dataGrid_selectionChanged(object sender, SelectionChangedEventArgs args)
{
// this works
// if nothing is selected, disable delete button and menu item
if (BooksDataGrid.SelectedItems.Count == 0)
{
button_deleteBook.IsEnabled = false;
menuItem_deleteBook.IsEnabled = false;
}
else
{
// delete command can now be executed, as shown in the binding in XAML
button_deleteBook.IsEnabled = true;
menuItem_deleteBook.IsEnabled = true;
}
}
- 要执行的删除命令。到目前为止还不清楚的是如何将参数传递给在 ViewModel 中实现的命令(视图为
DataContext)。我是 WPF 的新手,并试图了解命令的工作原理。具体来说,此命令应采用IEnumerable<string>的参数,或者可能是string的集合。我已经完成并测试了deleteAction方法。string对象将是DataGrid的选定行的“ISBN”列中的值。
【问题讨论】:
-
可以将
CommandParameter绑定到DataGrid.SelectedItem属性,该属性返回当前选中的行数据模型。
标签: c# .net wpf datagrid command