开发者

how to implement delayed MouseEnter event with Silverlight and Reactive extensions?

开发者 https://www.devze.com 2023-04-12 06:55 出处:网络
I\'m trying to implement a delayed MouseEnter event handler in my Silverlight UI. Having done this the \'classic\' way, with DispatcherTimer etc., I\'m now trying to do the same using Reactive extensi

I'm trying to implement a delayed MouseEnter event handler in my Silverlight UI. Having done this the 'classic' way, with DispatcherTimer etc., I'm now trying to do the same using Reactive extensions. This is supposed to be more concise and easy to read, but somehow I can't achieve the goal, which is:

  • when mouse enters some UI control, a method needs to be called,
  • but it should be done only after a certain amount of time passes, i.e. 1000 ms, in which time the mouse remains inside the control
  • so if mouse leaves the control before that period, nothing should happen at all, the event should be 'cancelled'

I went through the RX documentation, whi开发者_JAVA百科ch is fairly abstract and examples of such practical sort are rather non-existent. Based on some examples found online I came up with something like this:

    Observable.Throttle(
      Observable.FromEventPattern(LanguageSelector, "MouseEnter"), TimeSpan.FromSeconds(2))
      .TakeUntil(Observable.FromEventPattern(LanguageSelector, "MouseLeave"))
      .ObserveOnDispatcher()
      .Subscribe(e =>
      {
          ShowPopup();
      });

It seems to work fine, but only once. Once mouse leaves the control, it won't work any more, my popup never gets triggered any more. Any better ideas on how to do this?

thanks in advance!


The reason your solution only fires once is the TakeUntil. Once a MouseLeave happens, your observable is disposed. The SelectMany method can be used to overcome this:

var mouseEnter = Observable.FromEventPattern(LanguageSelector, "MouseEnter");
var mouseLeave = Observable.FromEventPattern(LanguageSelector, "MouseLeave");

mouseEnter
    .SelectMany(mousePos => 
        Observable.Timer(TimeSpan.FromSeconds(2)).ObserveOnDispatcher()
        .TakeUntil(mouseLeave))
    .Subscribe(e => ShowPopup());
0

精彩评论

暂无评论...
验证码 换一张
取 消