Search
On this page
Archives
RSS 2.0 Categories
Blogroll
Disclaimer
Powered by: newtelligence dasBlog 2.0.7226.0
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
Send mail to the author(s) E-mail
Yngwie Malmsteen syndrome (Silverlight 2 Scroller revisited)#

Earlier this month, I blogged about a Silverlight 2 Scroller control that I had labored over for the better part of a weekend.  The entire time I was working on this Scroller, I had this small, dirty feeling that what I had created was somehow way more than what I needed to accomplish my end goal.  But, time was short, it got the job done and I figured that I could always revisit it at some point.  

Fast forward a few days as I was reading Shawn Wildermuth's blog and I come across his post on the Silverlight ItemsControl and realized what that dirty feeling was all about.  I was exactly the guy he was talking about that was trying to bastardize the Silverlight ListBox into something else...namely the ItemsControl.  So, I revisited the Scroller and was able to remove about 50% or more of the code and still achieve my goal.  No custom ListBox, etc. 

I think it's part of most any process, really.  As you work on making something better you tend to keep adding and adding more code until you reach a saturation point where you need to step back and just start removing things. 

It made me think of so many guitarists in the 80's that just kept adding and adding notes and playing faster and faster until the music just became guitar masturbation instead of anything musical.  (These guys wouldn't have known a whole note if it hit them in the face). On the other hand, you take someone like David Gilmour that can play one note and absolutely convey way more than the shred monsters could ever muster.  It's all part of the learning process.  There's a curve graphed somewhere (I'm sure) that shows the guitarist's ascension to knowing when NOT to play.

So, who is Yngwie Malmsteen and what does he have to do with this post?  You can find out more than you ever wanted to know about Yngwie here.  Yngwie was the poster boy for never quite knowing when to stop adding notes and he flashed before my eyes when I looked back and my original Scroller code.  Anyway, thanks Shawn for saving me from that fate. 

The updated code is here.  Here is the live demo.

I'll leave the original code here in case you want to get it and make fun of me. 

Thursday, January 22, 2009 6:39:29 PM (GMT Standard Time, UTC+00:00)
  Comments [0]  | 
Silverlight System.ExecutionEngineException#

Just a quick note that will hopefully save someone the pain that I just went through chasing yet another exception in Silverlight with nothing to go on from Visual Studio.  (I really hope that there is some better feedback coming on Silverlight applications when you hit a runtime error in the future).  Anyway, I was digging in my App.xaml today to do a bit of much-needed clean up and then started getting System.ExecutionEngineException being thrown at runtime.  I was just about to the point of pulling out WinDbg (see this post on that) and I decided that maybe Blend could help me out.  After all, it really does owe me one for all the times it wouldn't load my xaml without telling me why.

So, I opened the project in Blend and sure enough, it gave me the old "Invalid XAML" message that I was expecting when I attempted to open my app.xaml.  However, it also gave me a bunch of errors about not finding properties from one of my styles.  I took a wild shot and clicked the View XAML Code link that Blend offered.  It placed me on a style that I had added earlier and I immediately noticed that I had left off the TargetType attribute.  Adding this cured the problem. 

And for those that just scan for the code...

Bad:

        <Style x:Key="MyButtonStyle">
            <Setter Property="FontSize" Value="10" />
        </Style>

Good:

        <Style x:Key="MyButtonStyle" TargetType="Button">
            <Setter Property="FontSize" Value="10" />
        </Style>

Thursday, January 15, 2009 8:46:11 PM (GMT Standard Time, UTC+00:00)
  Comments [1]  | 
Silverlight 2 Scroller#

Last week I had opportunity to really dive into some fun with a Silverlight 2 ListBox.  It all started with a requirement for a simple Scroller control.  You know, the simple left-to-right scrollers that you see in many applications?  I've seen them in several places, yet when I searched around for a Silverlight version that met my criteria I came up empty.  I have seen many great Image Carousel controls around, but overall the majority of them were not quite "calm enough" for a typical Line of Business application and I wasn't really intending on using images only.  There were some really great "pieces" that I found as I attempted to assemble this control and now that I have a functional version, I thought I'd share it with the community.       

The first challenge here was that I needed to have two horizontal rows of items in the Scroller.  Thanks to a post over at The Problem Solver and the WrapPanel from the Silverlight Toolkit, I was able to pull this off pretty easily.  So, I went to work on a custom template for a ScrollBar.  My initial thought here was that I'd stretch the ScrollBar to the Height of the ListBox, delete the Thumb, make the Background Transparent, and delete the Large Increase/Decrease controls.  This worked great, but the scrolling was what you would typically get when clicking the Small Increase/Decrease portions of a ScrollBar (i.e. the little arrows).  What we really needed was for each click to move to the next/previous column of items. 

At this point, I decided to lose the custom template for the ScrollBar and just go with a pair of RepeatButtons for the Previous/Next buttons so that I could have a little more control over things.  As I didn't want to see the ScrollBar, I had to hide it by setting the HorizontalScrollBarVisibility and the VerticalScrollBarVisibility to Hidden in the ControlTemplate of the ListBox. 

The ScrollViewer (that is part of our ListBox) is what we want to manipulate to give this per-item scroll experience to the user.  There are a couple of important properties of the ScrollViewer that we care about.  First, the ScrollableWidth which represents the width of the area that can be scrolled.  You can envision this as placing all of the columns end-to-end (including those that are scrolled out of sight) and getting the total width.  Secondly, the HorizontalOffset which is simply the indicator of the current scroll position (relative to the entire ScrollableWidth).  Using these two properties and the ItemWidth, we can compute how far to move the ScrollViewer for each click of our Previous/Next buttons. 

Since I needed direct access to the ScrollViewer in my ListBox and its not readily available from the default ListBox, I decided to create a custom control with a ScrollHost property.  I saw this little trick used in the ItemContainerGenerator class of the Silverlight Toolkit (which has some really great utility code along with the awesome controls....well worth your time to investigate that).  Also, since I was using a WrapPanel as my ItemsPanelTemplate and I needed the ItemWidth for my calculations and since WrapPanel just happens to have an ItemWidth property, I decided to expose that as a property as well.  I overrode the PrepareContainerForItemOverride() method in my custom ScrollerListBox in order to set these properties.  This worked pretty well and with a little math and a call to ScrollViewer.ScrollToHorizontalOffset(), I was able to create the scrolling behavior that I needed. 

But....wouldn't it be cool if the scrolling was animated?  ...it is Silverlight after all and every demo that I've ever seen at a conference with Silverlight has animation.  This proved to be a little more difficult as you can't directly animate HorizontalOffset.  While searching for a way to solve that, I came across a really great solution on Rob's Usability Development blog for creating an AnimationHelperControl to give you something to animate.  His post also made use of his excellent AnimateTo extension methods that he describes in another post.

As I didn't want to hard code the amount of time it took to animate the scroll, I added a ScrollTime Dependency Property to the ScrollerControl and was able to set that declaratively in my Page.Xaml.  

I think the final result gives a nice subtle use of animation that doesn't distract the user from their data.  (As an aside...for a REALLY nice usage of animation in a Silverlight application, check out the one that Billy Hollis shows in this video on dnrTV).

My demo uses employees that I've generated in a TestData class and then binds the various fields to the ItemTemplate of my ListBox using standard Silverlight DataBinding.  I was a bit too lazy to create a separate image for each of my employees, so I used the same image for each.  These images could just as easily be streamed from the database, but that's a different post.

Here is the live demo.

Here is the project source.

I have a few more ideas for the ScrollerControl such as the ability to drag between the items (sort of like the iPhone).  Anyway, I'll post those as I implement them. 

Sunday, January 11, 2009 7:44:44 AM (GMT Standard Time, UTC+00:00)
  Comments [0]  | 
Initializing the FROM value of a Silverlight 2 Animation#

Recently, I was attempting to create my own popup dialog. I had specific requirements in mind for this dialog, including: 

  1. I wanted to animate the Width/Height from 0x0 to the ActualWidth/ActualHeight
  2. I wanted to animate the Opacity from 0 to 1
  3. I wanted to animate the Top/Left properties from the point of mouse click (an icon in my case) to the center of the screen and back to the original point of mouse click when the user closed the dialog

All of these are fairly easy to accomplish using a Storyboard with an x:Name specified.  In the case of my requirement #3 above, I merely needed to set the From value of my animation and call the Begin() method, like so (for purposes of illustration, I'll confine this to the Canvas.Left property only...you can apply the same logic to the Canvas.Top property and it's all in the accompanying project):

<Storyboard x:Name="MoveDialogStoryboard">
  <DoubleAnimation
       x:Name="theDialogAnimation"
       Storyboard.TargetName="theDialog" 
       Storyboard.TargetProperty="(Canvas.Left)"
      To="0" Duration="0:0:0.5" />
  </Storyboard>

theDialogAnimation.From = 800;   // this value would actually come from getting the mouse position via GetPosition()
(MoveDialogStoryboard as Storyboard).Begin();

This all works as you would expect.  However, I really liked the idea of isolating all of my dialog states into one place and the Visual State Manager sounded like the perfect solution...that is, until I tried to set the FROM value programmatically and got hit with a NullReferenceException every time I tried to reference my named Animation. 

I tried several things and ended up posting my issue to the Silverlight forum where Shawn Wildermuth was kind enough to offer a solution.  Shawn's solution was to simply set the property to the value before calling GoToState() in my code.  This made perfect sense and I ran off to give it a try.  It worked...once.  My animation would fire once but then appear to be swallowed or ignored on subsequent clicks.  After further investigation, this turned out to be an artifact of the fact that I was never setting my VisualState back to the original state...something you don't have to do when using a Storyboard outside of the Visual State Manager.  So, that fixed that issue and Shawn's solution worked.  However, I didn't really see any way using this solution to animate back to the original point of mouse click.   

Either way, it didn't really satisfy my initial curiosity for WHY I couldn't programmatically set the FROM value when my animation was inside a Visual State Manager, so I pressed on.  Thanks to a couple of blog posts (here and here) and some pretty ugly LINQ, I was finally able to programmatically set the FROM value and have it animate my dialog from the original point of mouse click with a Storyboard inside of a VisualState like so: 

public void ShowDialog(Point startingPosition)
{
     Storyboard storyboard = Utils.FindStoryboard(LayoutRoot, "DialogStates", "Open");
     (storyboard.Children[0] as DoubleAnimation).From = startingPosition.X;
     (storyboard.Children[1] as DoubleAnimation).From = startingPosition.Y;
     VisualStateManager.GoToState(this, "Open", true);
}

// This is the definition of the extension method FindStoryboard() shown above (which is where the real work happens)
public static Storyboard FindStoryboard(this FrameworkElement parent, string groupName, string stateName)
{
     VisualState visualState = VisualStateManager.GetVisualStateGroups(parent)
         .Cast<VisualStateGroup>().Where(group => group.Name == groupName)
         .SingleOrDefault()
         .States.Cast<VisualState>()
         .Where(state => state.Name == stateName)
         .SingleOrDefault();

     if (visualState != null)
         return visualState.Storyboard;    

     return null;    
}

All of that being said, I didn't end up going this route nor do I recommend it.  It's way too brittle and just plain ugly in my opinion.  In the end, I chose to create my Open and Closed Storyboard animations for my popup dialog as standard Resource Storyboards where I don't have to reset the State before calling and I don't have to jump through hoops to set the value and, most importantly, I can set a name for the Animation and directly set the property value.  For the actual "modes" of my dialog (assuming there are multiple views for the dialog), I used the VSM to represent things like EntryView, EditView, etc.  I think this offers a much cleaner solution.

I've put together a quick demo to illustrate both calling the Storyboard directly and using a Storyboard in a VSM.  The live version is here and the project source is available here

Sunday, January 04, 2009 12:23:48 AM (GMT Standard Time, UTC+00:00)
  Comments [0]  | 
All content © 2010 , Rik Robinson