Procedural WPF


The previous sections explain how to use XAML to build WPF windows. By using XAML, you can define controls, resources, styles, templates, transformations, and even animations.

Behind the scenes, an application reads the XAML code, and then builds corresponding controls and other objects to make the user interface. Often, it’s easiest to build forms by using the XAML editor, but if necessary, your Visual Basic code can build exactly the same objects.

Tip 

Usually you should build the interface with XAML to increase the separation between the user interface and the code. However, it may sometimes be easier to build dynamic elements in code (for example, in response to data loaded at runtime, inputs from the user, or in response to errors).

For example, the following Visual Basic code adds a button to a WPF form:

  ' The button we will build. Private WithEvents btnClickMe As Button ' Build the user interface. Private Sub Window1_Loaded(ByVal sender As Object, _  ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded     ' Get the window's default Grid.     Dim grd As Grid = DirectCast(Me.Content, Grid)     ' Add a Button.     btnClickMe = New Button()     btnClickMe.Content = "Click Me"     btnClickMe.Margin = New Thickness(5)     grd.Children.Add(btnClickMe) End Sub ' The user clicked the button. Private Sub btnClickMe_Click(ByVal sender As Object, _  ByVal e As System.Windows.RoutedEventArgs) Handles btnClickMe.Click     MessageBox.Show("Clicked!") End Sub 

The code starts by converting the window’s Content property into a Grid object. It then creates a Button, sets a couple of properties for it, and adds it to the Grid control’s Children collection.

The Button control’s variable is declared at the module level and includes the WithEvents keyword so that it is easy to catch the button’s Click event.

Example program AnimatedButton uses Visual Basic code to implement several of the techniques described earlier using XAML code. It creates a brush object and uses it to define a Style for buttons. It then creates three Buttons using that Style.

When the mouse moves over a button, the program’s code builds and plays an animation to enlarge the button. When the mouse moves off of the button, the code restores the button to its original size.

The following code executes when the program’s window loads and builds the user interface objects:

  Private WithEvents btnCenter As Button Private Const BIG_SCALE As Double = 1.5 Private Sub Window1_Loaded(ByVal sender As Object, _  ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded     ' Make a style for the buttons.     Dim br_button As New RadialGradientBrush( _         Colors.HotPink, Colors.Red)     br_button.Center = New Point(0.5, 0.5)     br_button.RadiusX = 1     br_button.RadiusY = 1     Dim style_button As New Style(GetType(Button))     style_button.Setters.Add(New Setter(Control.BackgroundProperty, br_button))     style_button.Setters.Add(New Setter(Control.WidthProperty, CDbl(70)))     style_button.Setters.Add(New Setter(Control.HeightProperty, CDbl(40)))     style_button.Setters.Add(New Setter(Control.MarginProperty, New Thickness(5)))     ' Set the transform origin to (0.5, 0.5).     style_button.Setters.Add(New Setter(Control.RenderTransformOriginProperty, _         New Point(0.5, 0.5)))     ' Make a StackPanel to hold the buttons.     Dim stack_panel As New StackPanel()     stack_panel.Margin = New Thickness(20)     ' Add the Left button.     Dim btn_left As Button     btn_left = New Button()     btn_left.Style = style_button     btn_left.Content = "Left"     btn_left.RenderTransform = New ScaleTransform(1, 1)     btn_left.SetValue( _         StackPanel.HorizontalAlignmentProperty, _         Windows.HorizontalAlignment.Left)     AddHandler btn_left.MouseEnter, AddressOf btn_MouseEnter     AddHandler btn_left.MouseLeave, AddressOf btn_MouseLeave     stack_panel.Children.Add(btn_left)     ' Make the Center button.     btnCenter = New Button()     btnCenter.Style = style_button     btnCenter.Content = "Center"     btnCenter.RenderTransform = New ScaleTransform(1, 1)     btnCenter.SetValue( _         StackPanel.HorizontalAlignmentProperty, _         Windows.HorizontalAlignment.Center)     AddHandler btnCenter.MouseEnter, AddressOf btn_MouseEnter     AddHandler btnCenter.MouseLeave, AddressOf btn_MouseLeave     stack_panel.Children.Add(btnCenter)     ' Make the Right button.     Dim btn_right As New Button     btn_right.Style = style_button     btn_right.Content = "Right"     btn_right.RenderTransform = New ScaleTransform(1, 1)     btn_right.SetValue( _         StackPanel.HorizontalAlignmentProperty, _         Windows.HorizontalAlignment.Right)     AddHandler btn_right.MouseEnter, AddressOf btn_MouseEnter     AddHandler btn_right.MouseLeave, AddressOf btn_MouseLeave     stack_panel.Children.Add(btn_right)     Me.Content = stack_panel End Sub 

This code starts by declaring a Button control using the WithEvents keyword. The program makes three buttons, but only catches the Click event for this one. The code also defines a constant that determines how large the button will grow when it enlarges.

When the window loads, the code creates a RadialGradientBrush and defines its properties. It then creates a Style object that can apply to Button objects. It adds several Setter objects to the Style to set a Button control’s Background, Width, Height, Margin, and RenderTransformOrigin properties.

Next, the code creates a StackPanel object. This will be the window’s main control and will replace the Grid control that Visual Studio creates by default.

The program then makes three Button objects. It sets various Button properties, including setting the Style property to the Style object created earlier. It also sets each Button control’s RenderTransform property to a ScaleTransform object that initially scales the Button by a factor of 1 vertically and horizontally. It will later use this transformation to make the Button grow and shrink.

The code uses each Button control’s SetValue method to set its HorizontalAlignment property for the StackPanel. The code uses AddHandler to give each Button an event handler for its MouseEnter and MouseLeave events. Finally, the code adds the Button controls to the StackPanel’s Children collection.

The window’s Loaded event handler finishes by setting the window’s Content property to the new StackPanel containing the Button controls.

The following code shows how the program responds when the mouse moves over a Button:

  ' The mouse moved over the button. ' Make it larger. Private Sub btn_MouseEnter(ByVal sender As Object, _  ByVal e As System.Windows.Input.MouseEventArgs)     ' Get the button and its transformation.     Dim btn As Button = DirectCast(sender, Button)     Dim scale_transform As ScaleTransform = _         DirectCast(btn.RenderTransform, ScaleTransform)     ' Create a DoubleAnimation.     Dim ani As New DoubleAnimation(1, BIG_SCALE, _         New Duration(TimeSpan.FromSeconds(0.15)))     ' Create a clock for the animation.     Dim ani_clock As AnimationClock = ani.CreateClock()     ' Associate the clock with the      ' ScaleX and ScaleY properties.     scale_transform.ApplyAnimationClock( _         ScaleTransform.ScaleXProperty, ani_clock)     scale_transform.ApplyAnimationClock( _         ScaleTransform.ScaleYProperty, ani_clock) End Sub 

This code converts the sender object into the Button that raised the MouseOver event and retrieves its ScaleTransform object.

The code then creates a DoubleAnimation object to change the value 1 to the BIG_SCALE value (defined as 1.5 in the earlier Const statement) over a period of 0.15 seconds. It uses the object’s CreateClock statement to make an AnimationClock to control the animation. Finally, the code calls the ScaleTransformation object’s ApplyAnimationClock method twice, once for its horizontal and vertical scales. The result is that the Button control’s ScaleTransform object increases the Button control’s scale vertically and horizontally.

The btn_MouseLeave event handler is very similar, except that it animates the Button controls’ scale values, shrinking from BIG_SCALE to 1.

Example program GrowingButtons uses a similar technique to enlarge and shrink Button controls. Instead of using a simple DoubleAnimation to enlarge the Button controls, however, it uses DoubleAnimationUsingKeyFrames. This object lets you define a series of values that the animation should visit.

The following code shows how this program’s MouseEnter event handler works:

  Private Const BIG_SCALE As Double = 1.75 Private Const END_SCALE As Double = 1.5 Private Sub btn_MouseEnter(ByVal sender As Object, _  ByVal e As System.Windows.Input.MouseEventArgs)     ' Get the button and its transformation.     Dim btn As Button = DirectCast(sender, Button)     Dim scale_transform As ScaleTransform = _         DirectCast(btn.RenderTransform, ScaleTransform)     ' Create a DoubleAnimation that first     ' makes the button extra big and then     ' shrinks it to the "normal" big size.     Dim ani As New DoubleAnimationUsingKeyFrames()     Dim fr1 As New SplineDoubleKeyFrame(1.0, KeyTime.FromPercent(0.0))     Dim fr2 As New SplineDoubleKeyFrame(BIG_SCALE, KeyTime.FromPercent(0.5))     Dim fr3 As New SplineDoubleKeyFrame(END_SCALE, KeyTime.FromPercent(1.0))     ani.KeyFrames.Add(fr1)     ani.KeyFrames.Add(fr2)     ani.KeyFrames.Add(fr3)     ani.Duration = New Duration(TimeSpan.FromSeconds(0.33))     ' Create a clock for the animation.     Dim ani_clock As AnimationClock = ani.CreateClock()     'Dim ani_clock As AnimationClock = ani.CreateClock()     ' Associate the clock with the transform's     ' ScaleX and ScaleY properties.     scale_transform.ApplyAnimationClock( _         ScaleTransform.ScaleXProperty, ani_clock)     scale_transform.ApplyAnimationClock( _         ScaleTransform.ScaleYProperty, ani_clock)     ' Pop the button to the top of the stacking order.     grdMain.Children.Remove(btn)     grdMain.Children.Add(btn) End Sub 

Instead of simply growing the Button’s scale factors from 1 to 1.5, the animation first makes the Button grow by a factor of 1.75, and then shrink to a growth factor of 1.5. This overshoot gives the Button a cartoon-like style that is popular in user interfaces lately.

After it finishes animating the Button, the code removes the Button from the main Grid control’s Children collection, and then re-adds it to the collection to make the Button appear above the other Buttons.

Figure 26-12 shows program GrowingButtons in action with the mouse resting over the Tuesday button.

image from book
Figure 26-12: Program GrowingButtons uses Visual Basic code to animate buttons.

Other examples available for download at the book’s web page (www.vb-helper.com/vb_prog_ref.htm) demonstrate other procedural WPF techniques. For example, program ProceduralWPFCalculator builds a calculator similar to the one shown in Figure 26-7, but it builds its user interface in Visual Basic code.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net