In context of : .NET Core WPF application
I would like to : Create custom Command Class
for what : Binding basic custom action on Button click
I try lot of things but I always error generated in compilation. Can you help me to create this concept of code ?
My XAML window :
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MyApp" Height="800" Width="1200"
BorderThickness="5"
xmlns:local="clr-namespace:MyApp"
xmlns:test="clr-namespace:MyApp.Command"
>
<Window.CommandBindings>
<CommandBinding Command="test:MyCustomCommand" CanExecute="CanExecute" Executed="Executed" />
</Window.CommandBindings>
<Button Name="CreateOperation" Command="test:MyCustomCommand" Grid.Column="0" Width="70" Height="25" Margin="5">
<TextBlock>NEW</TextBlock>
</Button>
</Window>
MyCustomCommand.cs class :
using System;
using System.Windows.Input;
namespace MyApp.Command;
public class MyCustomCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object, bool> _canExecute;
public event EventHandler CanExecuteChanged;
public MyCustomCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object obj)
{
return true;
}
public void Execute(object obj)
{
}
public void Executed(object parameter)
{
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
In this context the CanExecute and Executed method declaration in XAML Command Binding is not found.
For me and all others that need help to create theirs custom class Command WPF, can you help me to find correct syntax for running command into custom class ?
First you need to remove the Window.CommandBindings. Also remove path to the command - test:. The command will be located in MainWindow code-behind as you requested. To pass a parameter to the command use CommandParameter property of the Button.
Add default constructor to the MyCustomCommand class.
And the MainWindow code-behind should look like this: