Delete row button in WPF DataGrid requires two clicks instead of one

395 Views Asked by At

I have a DataGrid with a delete button for each row, hooked to the Delete command. The button needs to be clicked twice to delete the row, which is not what I would like.

According to Snoop the button's IsEnabled == false initially, the first click enables it. This would seem to be the problem, so how can I make the button enabled before the user clicks?

I tried using a trigger to change IsEnabled, this is commented out in the code below, it didn't work.

Window1.xaml

<Window x:Class="WpfApp1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="Window1" Height="450" Width="800">
    <Grid>
        <DataGrid HorizontalAlignment="Left" Height="399" Margin="10,10,0,0" 
                  VerticalAlignment="Top" Width="772"
                  x:Name="dataGrid1" 
                  ItemsSource="{Binding ProxyServers}" 
                  CanUserAddRows="True" 
                  CanUserDeleteRows="True"
                  >
            <DataGrid.Columns>
                <DataGridTemplateColumn Width="SizeToCells">
                    <DataGridTemplateColumn.CellStyle>
                        <Style TargetType="{x:Type DataGridCell}" 
                            BasedOn="{StaticResource {x:Type DataGridCell}}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type DataGridCell}">

                                        <Button Command="DataGrid.DeleteCommand"  
                                            IsEnabled="True" x:Name="deleteButton" 
                                            Content="X">
                                           <!-- Make the button enable on mouse over?
                                                Didn't work.
                                                <Button.Style>
                                                <Style TargetType="Button">
                                                    <Style.Triggers>
                                                        <Trigger Property="IsMouseOver" 
                                                           Value="true">
                                                            <Setter Property="IsEnabled" 
                                                               Value="true" />
                                                        </Trigger>
                                                    </Style.Triggers>
                                                </Style>
                                            </Button.Style>-->
                                        </Button>

                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                            <Setter Property="IsEnabled" Value="True"/>

                        </Style>
                    </DataGridTemplateColumn.CellStyle>
                </DataGridTemplateColumn>

            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

Window1.xaml.cs

using System.ComponentModel;
using System.Windows;


namespace WpfApp1
{

    public partial class Window1 : Window
    {
        BindingList<Proxy> proxyServers;

        public Window1()
        {
            InitializeComponent();
            dataGrid1.DataContext = this;

            proxyServers = new BindingList<Proxy>();
            proxyServers.Add(new Proxy() { LocalURL = "http://localhost" });
        }

        public BindingList<Proxy> ProxyServers { get => proxyServers; set => proxyServers = value; }
    }

    public class Proxy
    {
        string localURL;

        public string LocalURL { get => localURL; set => localURL = value; }
    }
}
2

There are 2 best solutions below

2
Andy On BEST ANSWER

Have you considered something more like:

    <DataGridTemplateColumn Header="Delete">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Command="{Binding Deletecommand}"

You could use relativesource if you want the command in the parent view's daracontext. Pass the bound row object with commandparameter.

0
Jim W On

To elaborate on @Andy's answer. This is what I had to do.

  1. Add RelayCommand (this implementation is floating around the internet, I believe it comes from MVVMLite):

    using System;
    using System.Windows.Input;
    
    namespace WpfApp1
    {
    
    public class RelayCommand<T> : ICommand
    {
        #region Fields
    
        readonly Action<T> _execute = null;
        readonly Predicate<T> _canExecute = null;
    
        #endregion
    
        #region Constructors
    
        /// <summary>
        /// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
        /// </summary>
        /// <param name="execute">Delegate to execute when Execute is called on the command.  This can be null to just hook up a CanExecute delegate.</param>
        /// <remarks><seealso cref="CanExecute"/> will always return true.</remarks>
        public RelayCommand(Action<T> execute)
            : this(execute, null)
        {
        }
    
        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<T> execute, Predicate<T> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
    
            _execute = execute;
            _canExecute = canExecute;
        }
    
        #endregion
    
        #region ICommand Members
    
        ///<summary>
        ///Defines the method that determines whether the command can execute in its current state.
        ///</summary>
        ///<param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        ///<returns>
        ///true if this command can be executed; otherwise, false.
        ///</returns>
        public bool CanExecute(object parameter)
        {
    
            return _canExecute == null ? true : _canExecute((T)parameter);
    
        }
    
        ///<summary>
        ///Occurs when changes occur that affect whether or not the command should execute.
        ///</summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    
        ///<summary>
        ///Defines the method to be called when the command is invoked.
        ///</summary>
        ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to <see langword="null" />.</param>
        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }
    
        #endregion
    }
    }
    
  2. Define my own DeleteCommand rather than using the build-in one from DataGrid. I did this in the code-behind but in my real project it's going in the view model.

    private RelayCommand<object> _DeleteCommand;
    public RelayCommand<object> DeleteCommand => _DeleteCommand ?? (_DeleteCommand = new RelayCommand<object>((object o) => {
        var proxy = o as Proxy;
        proxyServers.Remove(proxy);
    
    }, (object o) => {
        if (o is Proxy)
        {
            return true;
        }
        else
        {
            return false;
        }
    }));
    

I couldn't use RelayCommand<Proxy> because the new item row is not a Proxy object. If I didn't have the new item row I could use RelayCommand<Proxy>.

  1. Remove this template definition in the XAML (because it is a ControlTemplate and not a DataTemplate, and it seems you need a DataTemplate if you want to pass the grid item to the command as a CommandParameter)

                    <DataGridTemplateColumn.CellStyle>
                        <Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource {x:Type DataGridCell}}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate >
    
                                        <Button Command="{Binding DeleteCommand,RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
                                                CommandParameter="{Binding  RelativeSource={RelativeSource AncestorType={x:Type local:Proxy}}}"
                                                IsEnabled="True" x:Name="deleteButton" Content="X">
    
                                        </Button>
    
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                            <Setter Property="IsEnabled" Value="True"/>
    
                        </Style>
                    </DataGridTemplateColumn.CellStyle>
    
  2. Add this instead

            <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Command="{Binding DeleteCommand,RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
                                            CommandParameter="{Binding}"
                                            IsEnabled="True" x:Name="deleteButton" Content="X">
    
                        </Button>
    
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>