我有一个在播放/暂停之间交替的按钮。我想看看是否有一个使用反应式扩展的好解决方案,而不是对布尔值进行翻转。这是对我想法的粗略估计。
var whenPlayClicked = Observable.FromEventPattern<EventArgs>(_playPauseButton, "Click")
.Take(1)
.Skip(1)
.Repeat();
var whenPauseclicked = Observable.FromEventPattern<EventArgs>(_playPauseButton, "Click")
.Skip(1)
.Take(1)
.Repeat();
Rx不提供任何本地运算符来简单地切换布尔值;但是,您可以编写一个非常优雅的Scan
查询来避免闭包。
void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Observable.FromEventPattern(_playPauseButton, "Click")
.Scan(false, (play, _) => !play)
.Subscribe(play => { if (play) Play(); else Pause(); });
}
private void Play()
{
_playPauseButton.Content = "Pause";
}
private void Pause()
{
_playPauseButton.Content = "Play";
}