How to enable a textbox and wait for criteria to be entered before delete operation in WPF

DPlug 41 Reputation points
2020-12-29T07:07:36.563+00:00

I am having trouble with deleting a record from my programme. I have a textbox which is disabled by default by the ReadOnly property which is bound to a boolean property of my ViewModel. The textbox permits the user to enter the ID as criteria for the record to be deleted. I have the delete code in my viewmodel, the code suppose to enable the textbox when the delete button is clicked the first time and wait for the user to enter the ID in the textbox and click the delete button the second time to carry out the delete operation. But instead, the code is not working as intended, the code enables the textbox and also run the delete operation without the user entering the ID when the delete button is clicked. In summary, the entire delete code block runs when the user click the delete button. Please how can I make the code to enable the textbox for ID an wait for the user to enter the ID and click the delete button the second time?
This is the code:

        private RelayCommand deleteCommand;

        public RelayCommand DeleteCommand
        {
            get { return deleteCommand; }
        }

        public void Delete()
        {
            MessageBoxResult result = MessageBox.Show("Are you sure you want to delete this record?", "Delete Operation", MessageBoxButton.YesNo, MessageBoxImage.Question,MessageBoxResult.No);
            if(result == MessageBoxResult.No)
            {
                return;
            }
            else
            {
                try
                {
                    IDEnabled = false;

                    var IsDeleted = ObjStudentService.Delete(NewStudent.Id);
                    if (!IsDeleted)
                    {
                        MessageBox.Show("Student Record Deleted", "Delete Operation", MessageBoxButton.OK, MessageBoxImage.Information);
                        LoadData();
                        NewStudent.Id = 0;
                    }
                    else
                    {
                        MessageBox.Show("Unable to Delete Record, ensure you enter the correct ID.", "Delete Operation", MessageBoxButton.OK, MessageBoxImage.Information);

                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message, "Exception Found", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }

        }

The "IDEnabled" is the property that disables the ReadOnly property of the ID textbox field so that the user can enter the ID for a particular record to be deleted.

I call the code in the constructor as follows:
public StudentViewModel()
{
ObjStudentService = new StudentService();
LoadData();
NewStudent = new Student();
deleteCommand = new RelayCommand(Delete);

This is my binding in the XAML for the delete button:
<Button x:Name="BtnDelete" Margin="10 0 0 0"
IsTabStop="False"
IsEnabled="{Binding Path=ButtonEnabled}"
Style="{StaticResource MaterialDesignRaisedAccentButton}"
ToolTip="Delete record"
Command="{Binding Path=DeleteCommand}"
Width="75">
Delete
</Button>

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,755 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,026 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,617 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,815 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,401 Reputation points
    2020-12-29T12:59:33.04+00:00

    Hello @DPlug

    I have a code sample that does not is a basic conceptual example on enable/disable a button which will work with other controls such as a TextBox.

    52052-1111.png

    Full source found here which is .NET Core 5, C# 9.

    RelayCommand

    using System;  
    using System.Windows.Input;  
      
    namespace FrameworkCanExecuteExample.Classes  
    {  
        public class RelayCommand : ICommand  
        {  
            private readonly Action<object> _execute;  
            private readonly Func<object, bool> _canExecute;  
      
            public event EventHandler CanExecuteChanged  
            {  
                add => CommandManager.RequerySuggested += value;  
                remove => CommandManager.RequerySuggested -= value;  
            }  
      
            public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)  
            {  
                _execute = execute;  
                _canExecute = canExecute;  
            }  
      
            public bool CanExecute(object parameter)  
            {  
                return _canExecute is null || _canExecute(parameter);  
            }  
      
            public void Execute(object parameter)  
            {  
                _execute(parameter);  
            }  
        }  
    }  
    

    View model

    using System;  
    using System.ComponentModel;  
    using System.Diagnostics;  
    using System.Runtime.CompilerServices;  
    using System.Windows.Input;  
      
    namespace FrameworkCanExecuteExample.Classes  
    {  
        public class MainViewModel : INotifyPropertyChanged  
        {  
            private string _connectionString;  
      
            public event PropertyChangedEventHandler PropertyChanged;  
      
            public MainViewModel() => ConfirmCommand = new RelayCommand(Confirm, CanConfirm);  
      
            public string ConnectionString  
            {  
                get => _connectionString;  
                set  
                {  
                    _connectionString = value;  
                    OnPropertyChanged();  
                }  
            }  
      
            public ICommand ConfirmCommand { get; }  
      
            protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)  
            {  
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
            }  
      
            private void Confirm(object parameter)  
            {  
                Debug.WriteLine("Do something for confirm");  
            }  
      
            private bool CanConfirm(object parameter)  
            {  
                return !string.IsNullOrWhiteSpace(_connectionString);  
            }  
        }  
    }  
    

    XAML

    <Window  
        x:Class="FrameworkCanExecuteExample.MainWindow"  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
        xmlns:classes="clr-namespace:FrameworkCanExecuteExample.Classes"  
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
        Title="MainWindow"  
        Width="300"  
        Height="100"  
        WindowStartupLocation="CenterScreen"  
        mc:Ignorable="d">  
      
        <Window.DataContext>  
            <classes:MainViewModel />  
        </Window.DataContext>  
      
        <Grid>  
            <Grid.RowDefinitions>  
                <RowDefinition />  
                <RowDefinition />  
            </Grid.RowDefinitions>  
            <Grid.ColumnDefinitions>  
                <ColumnDefinition />  
                <ColumnDefinition />  
            </Grid.ColumnDefinitions>  
      
            <TextBlock  
                Margin="0,0,10,0"  
                HorizontalAlignment="Right"  
                Text="Connection string:" />  
            <TextBox  
                Grid.Row="0"  
                Grid.Column="1"  
                Text="{Binding Path=ConnectionString, UpdateSourceTrigger=PropertyChanged}" />  
      
            <Button  
                Grid.Row="1"  
                Grid.Column="0"  
                Grid.ColumnSpan="2"  
                Command="{Binding ConfirmCommand}"  
                Content="Confirm" />  
        </Grid>  
    </Window>  
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.