绑定文本框 enter press to reactive command

Binding textbox enter press to reactive command

我有一个文本框绑定到具有以下内容的视图模型 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>

我正在尝试在我的视图模型中创建一个 ReactiveCommand,它会在视图中的 KeyBinding 事件被触发时触发。我很确定我的语法有误,但我不确定在查看文档后我需要做什么来修复它。这是我的相关视图模型代码:

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; }

      ...
}

一个明显的问题是 WhenAny returns System.IObservable<string> 其中 EnterCmd 期望类型 ReactiveUI.ReactiveCommand。我注意到的另一个问题是我无法用 getter 和 setter 声明 EnterCmd 因为我收到错误 'ReactiveCommand': static types cannot be used as parameters. 任何帮助将不胜感激。

然后使用这样的 reactiveCommand:

public class ReactiveCommand : ICommand, IObservable<object>
{
    private bool _canExecute = true;
    private readonly Subject<object> _execute = new Subject<object>();

    public ReactiveCommand(IObservable<bool> canExecute = null)
    {
        if (canExecute != null)
        {
            canExecute.Subscribe(x => this._canExecute = x);
        }
    }

    public bool CanExecute(object parameter)
    {
        return this._canExecute;
    }

    public void Execute(object parameter)
    {
        this._execute.OnNext(parameter);
    }

    public event EventHandler CanExecuteChanged;

    public IDisposable Subscribe(IObserver<object> observer)
    {
        return this._execute.Subscribe(observer);
    }
}

RxUI 命令的正确语法:

    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 是一个静态助手class(主要是工厂方法),实际类型是它的通用版本。