C#C
C#4y ago
27 replies
p. frost

Passing a string property to a command via a button CommandParameter in .NET 6

Hello

So I'm trying to pass a string (that's bound to a text field via a data context
<TextBox [...] Text="{Binding SearchString}"/>
which I made sure already works) using a button's
CommandParameter
. The relevant button code is as follows (I've hidden layout arguments)

<Button [...] Command="{Binding PerformSearch}" CommandParameter="{Binding SearchString}" />


PerformSearch
is a property of the class
MainViewModel
that I have defined as a custom class
    internal class SearchCommand : ICommand
    {
        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            System.Diagnostics.Debug.WriteLine("CanExecute(parameter) : parameter=" + parameter);
            return true;
        }

        public void Execute(object? parameter)
        {
            System.Diagnostics.Debug.WriteLine("Execute(parameter) : parameter=" + parameter);
        }
    }
    //...
    internal class MainViewModel : INotifyPropertyChanged
    {
        // ...
        public ICommand? PerformSearch { get; } = new SearchCommand();
        // ...
    }


This does however not work, pressing the button does call the command and I do see
CanExecute(parameter) : parameter=
Execute(parameter) : parameter=

in the program's output, however after testing
parameter
is null. If I pass a string directly instead of using a binding, I do get the string as an output
<Button [...] Command="{Binding PerformSearch}" CommandParameter="Hello" />

which produces
CanExecute(parameter) : parameter=Hello
Execute(parameter) : parameter=Hello


What am I doing wrong with my previous binding? Maybe this is the wrong way of handling button presses? I've seen people just use
CommandParameter="Binding"
and pass the whole ViewModel, and it does indeed pass the whole viewmodel, but I feel like it defeats the purpose of having a separate class handle the command.
Was this page helpful?