DarioSantarelli.Blog("UgiDotNet");

<sharing mode=”On” users=”*” />
posts - 176, comments - 105, trackbacks - 3

My Links

News


This is my personal blog. These postings are provided "AS IS" with no warranties, and confer no rights.




Tag Cloud

Archives

Post Categories

My English Blog

[Silverlight 2] Creare un Timer

Mi è capitato di aver bisogno di un timer per gestire il FadeIn/FadeOut di una Toolbar di un VideoPlayer custom. In pratica, la Toolbar deve scomparire automaticamente con un effetto "fadeout" (storyboard) quando il mouse si trova in aree diverse dell'UI per un certo periodo di tempo. Inizialmente pensavo che si potesse implementare un workaround andando ad agire invasivamente nel behaviour della storyboard di fadeOut (come in questo esempio), poi documentandomi un po' mi sono reso conto che la soluzione più consigliabile è in generale quella di utilizzare la classe DispatcherTimer (System.Windows.Threading). 
Nel mio caso è bastato quindi implementare un Timer custom come questo (il codice è stato opportunamente semplificato :D)

using System.Windows.Threading;

public class Timer : UserControl
{
 
private DispatcherTimer _dispatcherTimer;
 
private int _elapsed;

 
public int Duration { get; set; }       
 
public int TickInterval { get; set; }

 
public event EventHandler OnStart;       
 
public event EventHandler OnEnd;

 
public Timer()
 
{                       
   
_dispatcherTimer = new DispatcherTimer();            
   
_dispatcherTimer.Tick += new EventHandler(_dispatcherTimer_Tick);           
 
}

 
private void _dispatcherTimer_Tick(object sender, EventArgs e)
 
{
   
_elapsed += this.TickInterval;
   
if (_elapsed >= this.Duration)
   
{
     
Reset();  
     
if (OnEnd != null) OnEnd(this, null);               
   
}
 
}

 
public void Start()
 
{
   
_elapsed = 0;
   
_dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, this.TickInterval);
   
_dispatcherTimer.Start();                       
   
if (OnStart != null) OnStart(this, null);                       
 
}
 
 
public void Reset()
 
{
   
_elapsed = 0;
   
_dispatcherTimer.Stop();
 
}
}


A questo punto nello stage inseriamo il nostro timer:

<myns:Timer Name="timer" Duration="3500" TickInterval="100" OnStart="Timer_OnStart" OnEnd="Timer_OnEnd"></myns:Timer>

... e se dovessimo gestire due distinte storyboard di FadeIn e FadeOut, possiamo sfruttare gli eventi OnStart/OnEnd esposti dal timer per ottenere il risultato desiderato nel seguente modo:

private void Timer_OnStart(object sender, EventArgs e) { storyBoardFadeIn.Begin(); }

private
void Timer_OnEnd(object sender, EventArgs e)
{ storyBoardFadeOut.Begin(); }  


Niente di più facile :D.

Technorati Tag:

Print | posted on sabato 15 novembre 2008 22:06 | Filed Under [ Silverlight ]

Comments have been closed on this topic.

Powered by:
Powered By Subtext Powered By ASP.NET