2017-09-23 162 views
-1

我在學習ReactiveUI,所以我正在製作示例應用程序,但我遇到了問題InvokeCommand。基本上每次SearchPhrase屬性都改變了我的ShowSearchPhraseCommand應該被調用。WPF - ReactiveUI InvokeCommand不工作

這是我的觀點:

<StackPanel Grid.Column="1" Grid.Row="1" Orientation="Horizontal" 
    VerticalAlignment="Center" > 


    <TextBox Width="100" Height="20" 
    Text="{Binding Path=SearchPhrase, UpdateSourceTrigger=PropertyChanged}" /> 
</StackPanel> 

視圖模型:

public ReactiveCommand ShowSearchPhraseCommand { get; private set; } 

string _searchPhrase; 
public string SearchPhrase 
{ 
    get { return _searchPhrase; } 
    set { this.RaiseAndSetIfChanged(ref _searchPhrase, value); } 
} 

public SecondViewModel(IScreen hostScreen) 
{ 
    HostScreen = hostScreen; 

    // Commands 
    ShowSearchPhraseCommand = ReactiveCommand.Create(() => ShowSearchPhraseCommandHandler(SearchPhrase)); 

    // WhenAny 
    this.WhenAnyValue(x => x.SearchPhrase).Where(x => !string.IsNullOrWhiteSpace(x)).InvokeCommand(ShowSearchPhraseCommand); 
} 

private void ShowSearchPhraseCommandHandler(string searchPhrase) 
{ 
    Debug.WriteLine($"Phrase: {searchPhrase}"); 
} 

,這裏是我的問題:

enter image description here

回答

2

命令需要一個Unit

this.WhenAnyValue(x => x.SearchPhrase) 
    .Where(x => !string.IsNullOrWhiteSpace(x)) 
    .Select(_ => System.Reactive.Unit.Default) //<-- 
    .InvokeCommand(ShowSearchPhraseCommand); 

...除非你把它定義爲一個ReactiveCommand<string, Unit>

public ReactiveCommand<string, System.Reactive.Unit> ShowSearchPhraseCommand { get; private set; } 
... 
ShowSearchPhraseCommand = ReactiveCommand.Create<string>(ShowSearchPhraseCommandHandler);