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.
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>