如何在WPF中将Button绑定到DataGrid删除命令

时间:2014-06-23 09:04:33

标签: wpf mvvm commandbinding

我想通过单击MVG模式之上的DataGrid上方(不在内部)按钮来删除WPF DataGrid中的行。虽然行中的删除按钮本身有效,但它们有点难看(必须首先选择行),而且删除按钮旁边还有添加和编辑按钮,我认为删除按钮更适合那里。 我的ViewModel中的相应部分如下所示:

<Button Grid.Row="0" Grid.Column="0" Content="add"/>
<Button Grid.Row="0" Grid.Column="1" Content="edit"/>
<Button Grid.Row="0" Grid.Column="2" Content="delete"/>
<DataGrid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" 
    ItemsSource="{Binding dataTableListItems}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name"/>
        <!--I don't wan't to use these "in-Row" delete buttons-->
        <DataGridTemplateColumn Header="delete">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Command="Delete" Content="X"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

关于按钮的命令绑定如何看起来的任何想法?或者,如果始终启用行内删除按钮并且单击一个会删除相应的行而不需要先选择行,我也会感到满意

1 个答案:

答案 0 :(得分:4)

假设您正在使用MVVM,只需绑定到DataGrid的SelectedItem,并在调用Command时使用它。

示例ViewModel:

public class MyViewModel : INotifyPropertyChanged
{
    private Item _selectedItem;
    public Item SelectedItem 
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            RaisePropertyChanged("SelectedItem");
        }
    }

    private ObservableCollection<Item> _dataTableListItems;
    public ObservableCollection<Item> DataTableListItems 
    {
        get { return _dataTableListItems; }
        set
        {
            _dataTableListItems = value;
            RaisePropertyChanged("DataTableListItems")
        }  
    }


    public ICommand DeleteCommand { get; set; }

    public MyViewModel()
    {
        DeleteCommand = new RelayCommand(DeleteSelected);
    }

    private void DeleteSelected()
    {
        if (null != SelectedItem)
        {
            DataTableListItems.Remove(SelectedItem);
        }
    }
}

更新了XAML:

<Button Grid.Row="0" Grid.Column="0" Content="add"/>
<Button Grid.Row="0" Grid.Column="1" Content="edit"/>
<Button Grid.Row="0" Grid.Column="2" Content="delete" Command="{Binding DeleteCommand}"/>
<DataGrid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" 
    ItemsSource="{Binding dataTableListItems}"
    SelectedItem="{Binding SelectedItem}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name"/>
        <!--I don't wan't to use these "in-Row" delete buttons-->
        <DataGridTemplateColumn Header="delete">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Command="Delete" Content="X"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>