Does anyone know a good example of ReactiveCommand for ReactiveUI?

I am inexperienced, especially in MVVM, but trying to use ReactiveUI, and I do not understand the examples that I find that demonstrate ReactiveCommand. I used ICommand / DelegateCommand once before, but it is different and I do not get it.

What I'm trying to do is really simple. Click the button in the view and execute to execute the method in the view model. The examples that I find in everything include IObservable <>, and I do not understand this, because they do not explain what is connected with the complete noob that I am.

Basically, I am trying to use this as a learning experience, and I would like to somehow associate the Command property in xaml with the command (however this works, I don’t know), which causes a way to execute. There are no collections, I would just pass one int variable.

Thanks for the help. I really appreciate that.

Change Below is the code with Paul Bets's suggestions:

WITH#

public ReactiveCommand AddToDailyUsed { get; protected set; } public MainPageVM() { Initialize(); AddToDailyUsed = new ReactiveCommand(); AddToDailyUsed.Subscribe(AddToTodayUsedAction => this.AddToDailyUsedExecuted()); } private object AddToDailyUsedExecuted() { MessageBox.Show("AddToDailyUsedAction"); return null; } private void AddToDailyUsedAction(object obj) { MessageBox.Show("AddToDailyUsedAction"); } 

Xaml

 <Button Content="{Binding Strings.add, Source={StaticResource LocalStrings}}" Command="{Binding AddToTodayUsed}" Margin="-5,-10, -10,-10" Grid.Row="3" Grid.Column="2" /> 

Obviously I'm missing something. I inserted breakpoints in the AddToDailyUsedExecuted and AddToDailyUsedAction methods, and they are never reached.

Change the Constructor for the code behind the view:

 MainPageVM mainPageVM = new MainPageVM(); public MainPage() { InitializeComponent(); Speech.Initialize(); DataContext = mainPageVM; ApplicationBar = new ApplicationBar(); TaskRegistration.RegisterScheduledTask(); this.Loaded += new RoutedEventHandler(MainPage_Loaded); //Shows the rate reminder message, according to the settings of the RateReminder. (App.Current as App).rateReminder.Notify(); } 
+4
source share
1 answer

So, ReactiveCommand itself is an IObservable<object> - in this case, you can conceptualize IObservable as an event - this event fires when a command is invoked (i.e., when a button is clicked). So in your constructor you can write:

 MyCommand = new ReactiveCommand(); MyCommand.Subscribe(param => this.MyCommandHasExecuted()); 

However, what is neat about IObservable, which is not true for regular events, is that you can use LINQ for them:

 // Now, MyCommandHasExecuted only gets run when the UserName isn't null MyCommand.Where(param => this.UserName != null) .Subscribe(param => this.MyCommandHasExecuted()); 

Update: Your Xaml is attached to AddToTodayUsed , but your ViewModel command is called AddToDailyUsed . Could it be?

+7
source

All Articles