Monday, April 28, 2008

WPF Listbox Slide Animation in code behind VB.NET

'I just started work on WPF and the first thing i wanted to do was to animate a listbox item on selection change event. And the animation should be simple from left to right and back.
'So this the code to do it in code behind, for example if you have blank window then just paste the code below.
'Enjoy IT!

Imports System.Windows.Media.Animation

Class Window1
Private WithEvents ListBox2 As New ListBox
Private Sub Window1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.KeyDown
If e.Key = Key.Escape Then Me.Close()
End Sub
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Me.Content = Me.ListBox2
For i As Integer = 0 To 5
Dim tb As New TextBlock
tb.Text = Now.AddDays(i).ToLongDateString + " " + Now.AddMinutes(i).ToLongTimeString
tb.Width = 200
Dim b As New Border
b.Background = Brushes.LightBlue
b.BorderBrush = Brushes.Black
b.BorderThickness = New Thickness(2)
b.CornerRadius = New CornerRadius(45)
b.Padding = New Thickness(25)
'b.Width = 170
b.Child = tb

Dim sp As New StackPanel
sp.Children.Add(b)

Dim li As New ListBoxItem
li.Content = sp
li.Width = 250
li.HorizontalAlignment = Windows.HorizontalAlignment.Right

'AddHandler li.MouseEnter, AddressOf Me.ListBox1_MouseEnter
'AddHandler li.MouseLeave, AddressOf Me.ListBox1_MouseLeave
Me.ListBox2.Items.Add(li)
Next
End Sub

Private Sub ListBox1_MouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs)
'Me.DoAnimate(CType(sender, ListBoxItem), 150, 300)
End Sub
Private Sub ListBox1_MouseLeave(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs)
'Me.DoAnimate(CType(sender, ListBoxItem), 300, 150)
End Sub
Private Sub DoAnimate(ByVal li As ListBoxItem, ByVal ifrom As Integer, ByVal ito As Integer)
Dim da As DoubleAnimation = New DoubleAnimation()
da.From = ifrom
da.To = ito
da.Duration = New Duration(TimeSpan.FromSeconds(1))
li.BeginAnimation(ListBoxItem.WidthProperty, da)
End Sub
Dim oi As Integer = -1
Private Sub ListBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListBox2.SelectionChanged
Try
If Me.ListBox2.SelectedIndex <> -1 Then
Dim li As ListBoxItem = Me.ListBox2.Items(Me.ListBox2.SelectedIndex)
Me.DoAnimate(li, 250, 400)
If oi <> -1 Then
Dim li2 As ListBoxItem = Me.ListBox2.Items(oi)
Me.DoAnimate(li2, 400, 250)
End If
Me.oi = Me.ListBox2.SelectedIndex
Me.ListBox2.SelectedIndex = -1
End If
Catch ex As Exception
End Try
End Sub
End Class