Mrb
Mrb

Reputation: 21

How to bind command using ReactiveUI and WPF

I'm trying to learn ReactiveUI in WPF and I'm confusing on how to bind command using Reactive UI binding (not default Xaml binding). I read on ReactiveUI documentation that the correct way is to use the following instruction:

this.BindCommand(this.ViewModel, vm => vm.MyCommand, v => v.myControl);

Now if I have in MainWindowView.xaml (View):

        <Button x:Name="TestButton" Command="{Binding Click}" />

in MainWindowView code-behind:

    public partial class MainWindowView : Window
    {
       public MainWindowView()
       {
             InitializeComponent();
             DataContext = new MainWindowViewModel();
       }
    }

and in MainWindowViewModel (ViewModel):

    class MainWindowViewModel : ReactiveObject
    {
       public ReactiveCommand<Unit, Unit> ClickCommand { get; }

       public MainWindowViewModel()
       {
           ClickCommand = ReactiveCommand.Create(ClickMethod);
       }

       void ClickMethod()
       {
           // Code for executing the command here.
       }
   }

I don't know where insert and how to compose the first instruction :

this.BindCommand(this.ViewModel, vm => vm.MyCommand, v => v.myControl);

for my specific context.

Thank you very much for and an answer.

Upvotes: 1

Views: 2741

Answers (1)

Gene
Gene

Reputation: 46

The WPF samples referenced by Rodney Littles in the comment above are very good. For your case it should be something like this:

public partial class MainWindowView : ReactiveWindow<MainWindowViewModel>
{
    public MainWindowView()
    {
        InitializeComponent();
        ViewModel = new MainWindowViewModel();

        this
            .WhenActivated(disposables => {
                this
                    .BindCommand(this.ViewModel, vm => vm.ClickCommand, v => v.TestButton)
                    .DisposeWith(disposables);
        });
    }
}

Make sure you derive from ReactiveWindow<MainWindowViewModel> instead of Window. Also, instead of DataContext, use the inherited property named ViewModel.

Upvotes: 1

Related Questions