Silverlight Layout States with Reactive Extensions


image Here is a sample.

If you want iitems in a ListBox (or an ItemsControl) at startup to appear on the screen one by one, with a short delay, not all at once. Using ListBoxItem’s layout states took care of handling how an individual item would appear in the list, but I still needed to handle a short pause between each item being added to the list. Usually I resorted to using a Timer, which sorted out that needed delay for me, but that really felt like hacking that had nothing to do with the real problem. Reactive Extensions, however, offer a much elegant solution. The GenerateFromTime() construction operator is a close relative to the Generate() operator used in my previous blog entry, except GenerateFromTime() adds an important time dimension to generated sequence – the last parameter in this operator lets you specify a delay between each call to OnNext():


private readonly IObservable<string> numbers = 
             Observable.GenerateWithTime(1, i => i <= 8, i => i + 1, i => i.ToString(), i => TimeSpan.FromSeconds(.3));

private void OnLoaded(object sender, RoutedEventArgs e)
{
    numbers.ObserveOnDispatcher().Subscribe(AddImage);
}

private void AddImage(string image)
{
    list.Items.Add(image);
}

The above code snippet will produce an observable sequence of 8 strings,  progressing through these strings with a 0.3 seconds delay.
Note the ObserveOnDispatcher() operator again – GenerateWithTime uses a  timer operating on a background thread so we need to ensure the  AddImage() method is called on the UI thread.

Part 1: Silverlight Layout States with Reactive Extensions

Part 2: Lost in time? Zip it!

Part 3: Reactive Extensions #3: Windows Phone 7

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s