What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleDraw a rubberband ellipse with XAML in Visual Basic 2008
DescriptionThis example shows how to draw a rubberband ellipse with XAML in Visual Basic 2008.
KeywordsXAML, WPF, Visual Basic 2008, rubberband, rubberband ellipse
When the user presses the left mouse button, the following code creates a new Ellipse object. The Stroke property determines how the ellipse's border is drawn.

The call to e.GetPosition returns the mouse position relative to the control you pass it, in this case the Canvas canEllipse.

Notice the bizarre calls to Canvas.SetTop and Canvas.SetLeft. In XAML, the ellipse's Canvas.Top and Canvas.Left properties determine the control's position on the Canvas that contains it. Those are not really properties of the Ellipse object (they are provided by the Canvas) so you need to use this weird method to set their values. (Yes, this seems very strange. I suspect the WPF developers were overly influenced by XAML's structure rather than following the pattern used by previous controls where you would simply set the ellipse's Top and Left properties. Whatever.)

After creating the Ellipse, the code adds it to the Canvas control canEllipse.

start_point As Point
Private new_ellipse As Ellipse = Nothing

' Start the new ellipse.
Private Sub canEllipse_MouseLeftButtonDown(ByVal sender As _
    Object, ByVal e As _
    System.Windows.Input.MouseButtonEventArgs) Handles _
    new_ellipse = New Ellipse()
    new_ellipse.Stroke = Brushes.Purple
    new_ellipse.Width = 0
    new_ellipse.Height = 0

    start_point = e.GetPosition(canEllipse)
    Canvas.SetTop(new_ellipse, start_point.Y)
    Canvas.SetLeft(new_ellipse, start_point.X)

End Sub
When the mouse moves, the following code adjusts the ellipse's size. You cannot set the Width or Height properties to negative numbers so the code must figure out what the smaller X and Y coordinates are and use them for the control's upper left corner.
' Change the ellipse's size.
Private Sub canEllipse_MouseMove(ByVal sender As Object, _
    ByVal e As System.Windows.Input.MouseEventArgs) Handles _
    If new_ellipse IsNot Nothing Then
        Dim pt As Point = e.GetPosition(canEllipse)

        Canvas.SetTop(new_ellipse, Math.Min(pt.Y, _
        Canvas.SetLeft(new_ellipse, Math.Min(pt.X, _
        new_ellipse.Width = Math.Abs(pt.X - start_point.X)
        new_ellipse.Height = Math.Abs(pt.Y - start_point.Y)
    End If
End Sub
When the user releases the left mouse button, the following code sets new_ellipse to Nothing so future MouseMove events don't affect it.
' Finish the ellipse.
Private Sub canEllipse_MouseLeftButtonUp(ByVal sender As _
    Object, ByVal e As _
    System.Windows.Input.MouseButtonEventArgs) Handles _
    new_ellipse = Nothing
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.