Feeds:
Posts
Comments

Posts Tagged ‘Silverlight tips and tricks’

In Silverlight applications practically everything can be animated to provide visually pleasing transitions between changes in your application or web page. When you hide something that is currently visible, why have it just disappear when you can make it fade away or slide off to the edge of the page? Or both? Silverlight makes these kinds of effects so much easier than ever before… so take advantage of it!

Unfortunately, there’s one control that is surprisingly a pain to support this on… the grid control. Try to animate collapsing its rows or columns by animating ColumnDefinition.Width or RowDefinition.Height via:

<DoubleAnimation Storyboard.TargetName=”Column1″ Storyboard.TargetProperty=”Width” To=”0″ Duration=”00:00:00.5″/>

and you’ll quickly discover the following runtime error:

InvalidOperationException: DoubleAnimation cannot be used to animate property Width due to incompatible type.

It turns out, Width is not of type Double but instead is of type GridLength. And GridLength has a property called Value of type Double, but Value is ReadOnly so to change the width or height you have to create a new instance of the GridLength object and set it it to the Width Property. Unfortunately, this is not something that can be done in a DoubleAnimation (that I’m aware of).

The solution: Do it yourself! Add a Name to the root element of your page, animate your own property and have your your property wrap setting the Width property on the ColumnDefinition or RowDefinition.

<DoubleAnimation Storyboard.TargetName=”Myself” Storyboard.TargetProperty=”ColumnWidth” To=”0″ Duration=”00:00:00.5″/>

' Warning: This does not work from an animation
Public Property ColumnWidth() As Double
    Get
        Return Column1.Width.Value
    End Get
    Set(ByVal value As Double)
        Column1.Width = New GridLength(value)
    End Set
End Property
WAIT: Animations can only set DependencyProperties. So the above code will not work. Instead we need to turn this property into a DependencyProperty…

Private Shared ReadOnly ColumnWidthProperty As DependencyProperty = DependencyProperty.Register("ColumnWidth", GetType(Double), GetType(Page), New Windows.PropertyMetadata(AddressOf ColumnWidthChanged))
Private Property ColumnWidth() As Double
    Get
        Return DirectCast(GetValue(ColumnWidthProperty), Double)
    End Get
    Set(ByVal value As Double)
        SetValue(ColumnWidthProperty, value)
    End Set
End Property
Private Shared Sub ColumnWidthChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    DirectCast(d, Page).Column1.Width = New GridLength(DirectCast(e.NewValue, Double))
End Sub


Click To See

Download source code

Read Full Post »

« Newer Posts