Search code examples
c#xamluwpdispatchertimer

DispatcherTimer stacking - UWP


I'm currently working on a project in UWP and I have a CommandBar that I want to go from Hidden to Compact if the mouse moves. After five seconds (If the mouse dont move) the CommandBar should go back to Hidden again.

I dont get any errors, but when I move the mouse the CommandBar is going crazy and it's just flashing from Hidden to Compact when I move the mouse again. I think the problem is that the OnMouseMovement event is stacking upon itself.

This is my code for the mouse movement event:

public async void OnPointerMoved(object Sender, PointerRoutedEventArgs e)
{
    CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Compact;
    DispatcherTimer ButtonTimer = new DispatcherTimer();
    ButtonTimer.Interval = TimeSpan.FromSeconds(5);
    ButtonTimer.Tick += (sender, args) =>
    {
        CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Hidden;
    };
    ButtonTimer.Start();
}

Solution

  • I made a little test project to try it out and get you an answer, this is what I did :

    private DispatcherTimer Timer { get; set; }
    public MainPage()
    {
        this.InitializeComponent();
        CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Hidden;            
        Timer = new DispatcherTimer(){Interval = TimeSpan.FromSeconds(5) };
        Timer.Tick += (sender, args) => { 
            CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Hidden; 
            Timer.Stop();
        };
    
    }
    
    public async void OnPointerMoved(object Sender, PointerRoutedEventArgs e)
    {
        Timer.Stop();
        CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Compact;
        Timer.Start();            
    }
    

    Basically as @Evk said, you are creating a new timer every move of your mouse. So I declared a property for the timer and stop it then restart it when your mouse move.