【问题标题】:ReactiveUI/Reactive Extensions: how to clear ObservableAsPropertyHelperReactiveUI/Reactive Extensions:如何清除 ObservableAsPropertyHelper
【发布时间】:2014-02-16 10:22:39
【问题描述】:

我正在使用 ReactiveUI 框架来搜索世界上的机场列表。

我已经设置了 ObservableAsPropertyHelper,它是 ViewModel 中 SearchTerm 属性的建议机场的输出。以下是 ObservableAsPropertyHelper 的定义。在视图中,我有一个绑定到此属性的列表框。我希望能够明确地清除列表框(因为一旦用户选择了建议的项目,我想用所选机场填充 SearchTerm 并清除建议的列表)。有没有一种优雅的方式来实现这一点?

var searchTerms = this.ObservableForProperty(x => x.SearchTerms).Where(x => canSearch).Value().Throttle(TimeSpan.FromMilliseconds(500));
var searchResults = searchTerms.SelectMany(SearchAirports);
var latestResults = searchTerms.CombineLatest(searchResults, (s, r) => r.SearchTerm != s ? null : r.AirportLiteWithWeights).Where(x => x != null);
_airportLiteWithWeights = latestResults.ToProperty(this, x => x.AirportLiteWithWeights);

【问题讨论】:

    标签: c# wpf autocomplete system.reactive reactiveui


    【解决方案1】:

    我会这样做 - 这有点棘手,因为实际的事件序列会反馈到自身(即选择一个项目集 SearchTerms)

    // The act of selecting an item is very ICommand'y, let's model it
    // as such.
    ReactiveCommand SuggestionItemSelected = new ReactiveCommand();
    
    // Important to *not* signal a change here by touching the field
    // so that we avoid a circular event chain
    SuggestionItemSelected.Subscribe(x => _searchTerms = x);
    
    // NB: Always provide a scheduler to Throttle!
    var searchTerms = this.WhenAnyValue(x => x.SearchTerms)
        .Where(x => canSearch)
        .Throttle(TimeSpan.FromMilliseconds(500), RxApp.MainThreadScheduler);
    
    // Select + Switch will do what you were trying to do with CombineLatest
    var latestResults = searchTerms
        .Select(SearchAirports);
        .Switch()
    
    // The listbox is the combination of *Either* the latest results, or the
    // empty list if someone chooses an item
    var latestResultsOrCleared = Observable.Merge(
        latestResults,
        SuggestionItemSelected.Select(_ => new List<Results>()));
    
    latestResultsOrCleared
        .ToProperty(this, x => x.AirportLiteWithWeights, out _airportLiteWithWeights);
    

    【讨论】:

    • 谢谢保罗!但是 _searchTerms = x 不会更新 UI....顺便说一句..我今天学到了一些新东西。 Switch() 方法确实适合这种情况!谢谢!
    • 感谢 Paul,我能够使用此解决方案。但是我使用的是 RxUI 7 并且基本上使用了一个空命令来实现它。这个版本有没有更优雅的解决方案是没有 ReactiveCommand.Create();所以我使用 this.CancelCommand = ReactiveCommand.Create(() => { });
    猜你喜欢
    • 2013-05-16
    • 2023-03-23
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多