Home > Blockchain >  How to delete from DataGrid in WPF?
How to delete from DataGrid in WPF?

Time:10-05

I've tried almost every solution on Stackoverflow I don't understand why my binding statement for button inside datagrid is not giving hit on the property in ViewModel. This is my DataGrid:

 <DataGridTemplateColumn Header="Delete">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Command="{Binding DataContext.DeleteButton, RelativeSource={RelativeSource AncestorType=UserControl}}">Delete</Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

And this is my Code in VeiwModel:

private ICommand _delete;

        public ICommand DeleteButton
        {
            get
            {
                if (_delete == null)
                {
                    _delete = new UserCommand(DeleteItemExecute, CanDeleteItemExecute);
                }
                return _delete;
            }
        }

CodePudding user response:

I do the same thing, but another way :

View code :

<Button Click="DeleteObject">
    <Image Source="../img/image_delete.png" Width="20" Height="20"/>
</Button>

Then on my model :

private void DeleteObject(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
    Object selectedObject = button.DataContext as Object;
}

CodePudding user response:

Added "Name" to my reference

<Page x:Class="InventoryManagementWPF.Views.InventoryPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:InventoryManagementWPF.Views"
      xmlns:viewmodel ="clr-namespace:InventoryManagementWPF.ViewModel"
      mc:Ignorable="d" 
      d:DesignHeight="450" d:DesignWidth="800"
      Title="InventoryPage"
  ------>    x:Name="_window">  <------------- Added this change only
<Button Command="{Binding DataContext.DeleteButton, ElementName=_window}" CommandParameter ="{Binding}">Delete</Button>

Else everything is the same. This worked for me. I found the solution here

  • Related