2

I am using the Reactive UI events expansion to Reactive UI.

Just playing around getting events to connect to the ViewModel.

Originally I had in my constructor of my View

        this.Events().KeyDown.Select(x => x.Key).InvokeCommand(ViewModel.NewTextCommand);

However, this has the issue in the constructor the view model does not exist yet. I considered adding a WhenAnyValue and setting up the Invoke but not sure if this could lead to memory leaks.

At the moment I have

        this.Events().KeyDown.Select(x => x.Key).Subscribe(
            x =>
            {
                if (ViewModel != null)
                {
                    if (ViewModel.NewTextCommand.CanExecute(x))
                    {
                        ViewModel.NewTextCommand.Execute(x);
                    }
                }
            });

This seems a bit clumsy though.

1 Answer 1

4

You can definitely use WhenAnyValue, but there's also a built-in InvokeCommand overload in ReactiveUI to do this:

this.Events().KeyDown.Select(x => x.Key).InvokeCommand(this, v => v.ViewModel.NewTextCommand);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.