绑定文本框输入按到反应命令

时间:2015-08-06 13:12:50

标签: c# wpf system.reactive reactiveui

我有一个文本框绑定到具有以下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

一个明显的问题是,System.IObservable<string>会返回EnterCmd,其中ReactiveUI.ReactiveCommand需要类型EnterCmd。我注意到的另一个问题是,我无法使用getter和setter声明'ReactiveCommand': static types cannot be used as parameters.,因为我收到错误k_th_element(X,[X|_],1). k_th_element(X,[_|L],K):- K>1,K1 is (K-1),k_th_element(X,L,K1). 任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

然后使用这样的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);
    }
}