How to bind Combobox to a command in ReactiveUI?

Viewed 1380

I was wondering what is the best way to bind the control properties to the CommandParameter in ReactiveUI?

The BindCommand below does not provide a way to pass the parameter. The overload either takes a property in view model or an IObservable<T> for parameters.

View

this.WhenActivated(subscription =>
{
    subscription(this.BindCommand(
                    this.ViewModel,
                    vm => vm.TextCommand,
                    v => v.ComboBox
                    ));
}

ViewModel

public class MainPageViewModel : ViewModelBase
{
    public ReactiveCommand<string, Unit> TextCommand { get; set; }


    public MainPageViewModel()
    {
        TextCommand = ReactiveCommand.CreateFromTask<string>(DoSomething);

    }

    private Task DoSomething(string selectedText)
    {
        return Task.Delay(3000);
    }
}

The DoSomething method is called with selectedText as null everytime.

I have tried passing the IObservable for ToggleSwitch, but the behaviour is not as expected.

View

IObservable<bool> toggleOn = this.WhenAnyValue(v => v.Toggle.IsOn);
this.WhenActivated(subscription =>
{
     subscription(this.BindCommand(
                this.ViewModel,
                vm => vm.ToggleCommand,
                v => v.Toggle, toggleOn));
}

ViewModel

ToggleCommand = ReactiveCommand.CreateFromTask<bool>(Toggled);

private Task Toggled(bool toggleState)
{
   return Task.Delay(3000);
}

In the above code I do managed to get the toggleState, but it is the last state not the new state of the ToggleSwitch. Also, I could not make this work of ComboBox. I think it is a very common to pass command parameters from view and there should be an easier way to achieve it. What am I missing? I am using UWP app.

Thanks

1 Answers

I guess you can only bind commands to events, not directly to properties (maybe I'm wrong).

What if you subscribe to the SelectedValueChanged (Can't remember the name of the event) event in the combobox and then fire the command manually?

this.ComboBox.Events().SelectedValueChanged
    .Select(_ => ComboBox.Text)
    .InvokeCommand(this, vm => vm.ViewModel.TextCommand);
Related