Skip to content

ReactiveCommand with CommandParameter not working? #349

@jcummings2

Description

@jcummings2

Does the CommandParameter for a ReactiveCommand get passed to the Execute method?

The only mention I see of it in connection with R3 is in closed issue #281. I'm not sure what UI framework was being used in that issue but the discussion implies that the CommandParameter should work. However, I have been unable to get a parameter to be passed in Avalonia and WPF.

I modified the sandbox/WpfApp1 example from the repository (based on commit 5acafe7) to make it as simple as possible. Here is the ViewModel:

public class CommandViewModel : IDisposable
{
    public BindableReactiveProperty<bool> OnCheck { get; }
    public ReactiveCommand ShowMessageBox { get; }
    public ReactiveCommand<string, Unit> ShowMessageBoxWithParameter { get; }

    public CommandViewModel()
    {
        OnCheck = new BindableReactiveProperty<bool>();
        ShowMessageBox = OnCheck.ToReactiveCommand(_ =>
        {
            MessageBox.Show("clicked");
        });
        ShowMessageBoxWithParameter = new(
            canExecuteSource: OnCheck,
            initialCanExecute: false,
            convert: (msg) =>
            {
                MessageBox.Show($"CommandParameter is {msg}");
                return Unit.Default;
            }
        );
    }

    public void Dispose()
    {
        Disposable.Dispose(OnCheck, ShowMessageBox);
    }
}
 

and the relevant portion of the XAML:

<Window x:Class="WpfApp1.MainWindow"
        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="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:CommandViewModel />
    </Window.DataContext>

    <StackPanel Margin="10">
        <Label Content="Command" />
        <CheckBox IsChecked="{Binding OnCheck.Value}" />
        <Button Content="Btn" Command="{Binding ShowMessageBox}" />
        <Button Content="Btn With CommandParameter" Command="{Binding ShowMessageBoxWithParameter}" CommandParameter="Passed value" />
    </StackPanel>
</Window>

As you would expect, both buttons are enabled when the checkbox is checked. The first or original button displays a messages box as before. The second button can be pressed but nothing happens. A breakpoint set in the convert lambda never gets hit. What do I need to do for it to work?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions