Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding textbox enter press to reactive command

I have a textbox bound to a view model with the following XAML:

<TextBox x:Name="usrTxt" Text="{Binding UserID, UpdateSourceTrigger=PropertyChanged}" 
    Margin="0,0,0,10" TextWrapping="Wrap" Height="50"
    VerticalAlignment="Bottom" ToolTip="User ID" FontSize="29.333" 
    VerticalContentAlignment="Center" Padding="15,0" TabIndex="0">
      <TextBox.InputBindings>
        <KeyBinding Key="Return" Command="{Binding EntrCommand}"/>
      </TextBox.InputBindings>
</TextBox>

I'm trying to create a ReactiveCommand in my view model that will trigger whenever the KeyBinding event in the view is fired. I'm positive that I have the syntax wrong for this, but I'm not sure what I need to do to fix it after looking at the docs. Here's my relevant view model code:

class MainViewModel : ReactiveObject
{
      private DbContext dbCtx;

      public MainViewModel()
      {
          dbCtx = new DbContext(Properties.Settings.Default.DbString);

          EnterCmd = this.WhenAny(x => x.UserID, x => x.Value)
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .Do(_ => IsLoading = true);

          EnterCmd.Subscribe(x =>
          {
                Console.WriteLine(x);
                IsLoading = false;
          });
      }

      public ReactiveCommand EnterCmd { get; private set; }

      ...
}

An obvious problem is that WhenAny returns System.IObservable<string> where as EnterCmd expects type ReactiveUI.ReactiveCommand. Another problem I noticed is that I can't declare EnterCmd with a getter and setter because I got the error 'ReactiveCommand': static types cannot be used as parameters. Any help would be appreciated.

like image 853
John Avatar asked Nov 06 '25 07:11

John


1 Answers

Proper syntax for RxUI command:

    public ReactiveCommand<object> EnterCmd { get; private set; }
    ObservableAsPropertyHelper<bool> _isLoading;
    public bool IsLoading { get { return _isLoading.Value; } }

    public MainViewModel()
    {
        EnterCmd = ReactiveCommand.Create(
            this.WhenAny(x => x.UserID, x => x.Value)
                .Select(x => !String.IsNullOrWhiteSpace(x)));

        EnterCmd.IsExecuting.ToProperty(this, x => x.IsLoading, out _isLoading);

        EnterCmd.Subscribe(x =>
        {
            Console.WriteLine(x);
        });

ReactiveCommand is a static helper class (factory methods mostly), the real type is the generic version of it.

like image 179
Gluck Avatar answered Nov 09 '25 03:11

Gluck