Board logo

標題: WPF學習日誌 ~2008年3月號~ [打印本頁]

作者: bauann    時間: 2008-3-24 19:28     標題: WPF學習日誌 ~2008年3月號~

大家一起衝吧 ~
下面會貼一些測試時的心得與程式碼,跟大家一起討論了,之後陸續有新增的也會開新主題貼出來 ~
下面文章是由Blog轉過來的,因為Blog上面會跑JavaScript不喜歡跑些有的沒的的朋友可以在這邊看

下面這邊有個學習WPF,windows Form的相關學習資源,有一些Vedio可以看,對於這方面有興趣的朋友,千萬別錯過了,戴好耳機,抓緊滑鼠,咱們出發啦~


WindowsClient.net

[ 本帖最後由 bauann 於 2008-3-24 19:38 編輯 ]
作者: bauann    時間: 2008-3-24 19:31

最近要開始K書,練習WPF相關的東西,書是K這本

雖然Code的部分都是C#不過應該是不會差太多的~剛開始沒多久,按照書上給的範例練習了一下,順便把練習的程式碼貼出來,想看看WPF的朋友也可以測看看。
首先當然要先建立我們的環境,如果你還沒有安裝.Net framework3.0的話可以參考這一篇
設定好環境之後,建立一個新的專案(這邊我還是用VS2005+延伸套件來做)

之後會看到一個空空的Form,可以看看左邊的工具箱,這時候跟一般做WIndows Form應用程式的時候已經是不一樣了~接下來在方案總管的地方選擇View Code

換到程式碼檢視的部分貼上下面的程式碼(這個範例主要是當滑鼠移動的時候會改變背景的顏色,越靠近中心點顏色會越偏白色)
  1. ' Interaction logic for Window1.xaml
  2. Partial Public Class Window1
  3.     Inherits System.Windows.Window
  4.     Dim Brush As New SolidColorBrush(Colors.Black)
  5.     Public Sub New()
  6.         InitializeComponent()
  7.     End Sub
  8.     Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
  9.         Me.Title = "Vary the background"
  10.         Me.Background = Brush
  11.     End Sub
  12.     Private Sub Window1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles Me.MouseMove
  13.         Dim H As Double = ActualHeight - 2 * SystemParameters.ResizeFrameHorizontalBorderHeight
  14.         Dim W As Double = ActualWidth - 2 * SystemParameters.ResizeFrameVerticalBorderWidth
  15.         Dim ptMouse As New Point
  16.         ptMouse = e.GetPosition(Me)
  17.         Dim ptCenter As New Point(W / 2, H / 2)
  18.         Dim vectMouse As Vector = ptMouse - ptCenter
  19.         Dim Angle As Double = Math.Atan2(vectMouse.Y, vectMouse.X)
  20.         Dim vectEllipse As New Vector(W / 2 * Math.Cos(Angle), H / 2 * Math.Sin(Angle))
  21.         Dim byLevel As Byte = (255 * (1 - Math.Min(1, vectMouse.Length / vectEllipse.Length)))
  22.         Dim Clr As Color = Brush.Color
  23.         Clr.R = byLevel
  24.         Clr.G = byLevel
  25.         Clr.B = byLevel
  26.         Brush.Color = Clr
  27.     End Sub
  28. End Class
複製代碼

作者: bauann    時間: 2008-3-24 19:33     標題: 取得視窗(工作區)的長寬

*Note 本篇使用的開發工具為Visual Studio 2008(.Net framework版本為3.0
在以往要取得長、寬的部分我們會很自然的想到要用Height跟Width屬性,在WPF中建議您用ActualHeight與ActualWidth這兩個屬性(這兩個屬性都是唯讀的),您可以用VS2008開一個新的WPF應用程式專案,之後用下面程式碼來測試
  1. Private Sub Window1_SizeChanged(ByVal sender As Object, ByVal e As System.Windows.SizeChangedEventArgs) Handles Window1.SizeChanged
  2.         Me.Title = "Height:" & Me.ActualHeight & " Width:" & Me.ActualWidth
  3.         'Me.Title = "Height:" & Me.Height & " Width:" & Me.Width
  4.     End Sub
複製代碼
在改變視窗大小的時候,兩種方式都可以正確的顯示目前的大小,但是當我按下最大化按鈕的時候,直接抓Height與Width的部分確不會反應出變化。
作者: bauann    時間: 2008-3-24 19:35

Note:本篇工具使用VS2008,.Net framework版本3.5
這篇功能測試是每秒會變換Form的背景圖片,話先說在前頭,這篇單純的只是熟悉一下WPF相關物件的使用方式,不會看到WPF的"特異功能",單就功能上來看VS2005也是很輕易的可以完成的。
首先,有些東西要了解一下,像是WPF中並沒有直接提供Timer的控制項,那怎麼做呢?請參考下面這篇
請教WPF form沒有Timer元件了嗎??
好,下面我們來看看程式碼吧
  1. ''宣告Timer物件
  2.     Dim myT As Threading.DispatcherTimer
  3.     ''宣告Image物件
  4.     Dim img As Image
  5.     Dim B As BitmapImage
  6.     Dim ImagePath() As String
  7.     Dim Count As Integer = 0
  8.     Dim u As Uri
  9.     Dim R As New Random
  10.     Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
  11.         ''設定標題列文字
  12.         Me.Title = "WPF Text"
  13.         ''取得圖片檔案路徑
  14.         ImagePath = IO.Directory.GetFiles("D:\圖檔\JPG\App","*.jpg")
  15.         u = New Uri(ImagePath(0))
  16.         B = New BitmapImage
  17.         B.BeginInit()
  18.         B.UriSource = u
  19.         B.EndInit()
  20.         img = New Image
  21.         img.Source = B
  22.         img.Stretch = Stretch.UniformToFill
  23.         Me.Content = img
  24.         ''Timer相關設定
  25.         myT = New Threading.DispatcherTimer
  26.         myT.Interval = New TimeSpan(0, 0, 1)
  27.         AddHandler myT.Tick, AddressOf Timer_Tick
  28.         myT.Start()
  29.     End Sub
  30.     Private Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
  31.         On Error Resume Next
  32.         If (Count + 1) > (ImagePath.Length - 1) Then
  33.             Count = 0
  34.         Else
  35.             Count += 1
  36.         End If
  37.         u = New Uri(ImagePath(Count))
  38.         B = New BitmapImage
  39.         B.BeginInit()
  40.         B.UriSource = u
  41.         B.EndInit()
  42.         img.Source = B
  43.         ''亂數旋轉圖片的角度
  44.          Randomize()
  45.         img.LayoutTransform = New RotateTransform(R.Next(1, 100))
  46.     End Sub
複製代碼
值得一提的是,在指定BitmapImage的UriSource時,前後我們都會加上Init相關的動作,你可以將這兩行註解掉看看有什麼不同。
相關參考



作者: bauann    時間: 2008-3-24 19:40     標題: StackPanel

前面我們測試過幾篇有關WPF的應用程式,不知道有沒有發現,我們沒有辦法指定兩個以上的東西(物件)給Content屬性,WIndow的COntent、Button的Content等等,那怎麼辦呢?總不能用來用去都是使用一個東東而已吧..所以接下來我們要測試一些有關"容器"的部分,在WPF中有下面幾種容器 ,這篇只會提到StackPanel的部分,有興趣的朋友可以先自行測試看看,或是到MSDN去看看相關細節;好,下面來看看測試的程式碼吧
  1. Dim sp As StackPanel
  2.     Dim rnd As Random
  3.    
  4.     Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
  5.         rnd = New Random()
  6.         sp = New StackPanel
  7.         sp.Background = Brushes.AliceBlue
  8.         Me.Content = sp
  9.         For i As Integer = 1 To 9
  10.             Dim btn = New Button
  11.             btn.Name = "Button" & i
  12.             btn.FontFamily = New FontFamily("Consola")
  13.             Randomize()
  14.             btn.FontSize = rnd.Next(10, 25)
  15.             ''用 "_" 設定當按下"alt"按鍵時出現的"快速鍵提示字"
  16.             btn.C & i
  17.             ''設定按鈕間的間隔
  18.             btn.Margin = New Thickness(5)
  19.             ''可以將下面兩行程式碼註解看看不同的地方
  20.             btn.HorizontalAlignment = Windows.HorizontalAlignment.Center
  21.             btn.VerticalAlignment = Windows.VerticalAlignment.Center
  22.             AddHandler btn.Click, AddressOf Button_Click
  23.             sp.Children.Add(btn)
  24.         Next
  25.         Me.SizeToContent = Windows.SizeToContent.WidthAndHeight
  26.         ''將下面程式碼註解掉並改變視窗大小,看看結果有何不同
  27.         Me.ResizeMode = Windows.ResizeMode.CanMinimize
  28.     End Sub
  29.     Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
  30.         MessageBox.Show(CType(sender, Button).Name)
  31.         If sp.Orientation = Orientation.Horizontal Then
  32.             sp.Orientation = Orientation.Vertical
  33.         Else
  34.             sp.Orientation = Orientation.Horizontal
  35.         End If
  36.     End Sub
複製代碼
程式執行之後可以看到StackPanel是以水平或是垂直的方向來排列控制項,這就是這個容器的特性了,其中我們在設定Button的屬性時有用到底線( _ ),程式執行的時候按下"alt"按鍵,你可以看到數字鍵的下面都出現了底線,按下"alt+1",就可以直接觸發Button1的Click事件了。
作者: bauann    時間: 2008-3-24 19:53     標題: 3DTools

Note:本篇開發工具使用VS2008,.net framework版本3.5
雖然XAML Code還不會但是還是很想嘗試看看WPF 3D的功能,在WIndowsClient看了Building an Interactive 3D Video Player的範例,實在是手很癢..於是乎就照著範例測試了一下,不過其中播放影片的那個UserControl的XAML Code我沒有阿..殘念,沒關係,我用老朋友Button來測試,嘿嘿..
首先要到CodePlex下載3DTools的Dll檔,上面有bin(編譯好的),或是scr(未編譯的),看你是想要用哪一種,檔案準備好了之後,把它加到我們專案的參考進來,下面我們就看看XAML Code吧
  1. <Window
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     xmlns:Inter3D="clr-namespace:_3DTools;assembly=3DTools"
  5.     x:Class="Window1"
  6.     Title="Window1" Height="346" Width="469">
  7.     <Window.Resources>
  8.         <MeshGeometry3D x:Key="palnMesh" Positions="-1,-1,0 1,-1,0 1,1,0 -1,1,0" TextureCoordinates="0,1 1,1 1,0 0,0" TriangleIndices="0 1 2 0 2 3" />
  9.     </Window.Resources>
  10.     <Grid>
  11.         <Inter3D:TrackballDecorator>
  12.             <Inter3D:Interactive3DDecorator>
  13.         <Viewport3D>
  14.             <Viewport3D.Camera>
  15.                 <PerspectiveCamera Position="1,1,10" LookDirection="0,0,-1"></PerspectiveCamera>
  16.             </Viewport3D.Camera>
  17.             
  18.             <ModelVisual3D>
  19.                 <ModelVisual3D.Content>
  20.                     <AmbientLight/>
  21.                 </ModelVisual3D.Content>      
  22.              </ModelVisual3D>

  23.              <Inter3D:InteractiveVisual3D  Geometry="{StaticResource palnMesh}">
  24.                 <Inter3D:InteractiveVisual3D.Visual>
  25.                             <Button Content="Cleck Me" />
  26.                         </Inter3D:InteractiveVisual3D.Visual>
  27.             </Inter3D:InteractiveVisual3D>
  28.         </Viewport3D>
  29.         </Inter3D:Interactive3DDecorator>
  30.         </Inter3D:TrackballDecorator>
  31.         
  32.     </Grid>
  33. </Window>
複製代碼
這邊可以下載VS2008的專案檔來看

執行程式之後,你可以按著滑鼠左鍵,然後移動滑鼠(嘿嘿..我的button會旋轉耶..),或是右鍵,可以拉近拉遠,很炫吧。
其中我們看看下面這幾行
  1. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  2.    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  3.     xmlns:Inter3D="clr-namespace:_3DTools;assembly=3DTools"
複製代碼
上面兩行是預設引入的,Inter3D是加上去的,這感覺像是引入(Imports)命名空間的感覺,有加進來的話才會有相關功能可以用,好啦,不多說了,馬上動手去測試看看吧。
另外Button的部分我們也可以改成下面這樣,也可以放影片喔
  1. <MEDIAELEMENT Source="D:\blendButton.wmv" />
複製代碼

作者: bauann    時間: 2008-3-24 20:34     標題: WrapPanel

這篇我們來測試一下第二個"容器",WrapPanel,它是怎麼來幫我們做排版的動作呢?
千言萬語勝不過按一下"F5",讓我們直接瞧瞧程式碼吧
  1. Dim wp As WrapPanel
  2.     Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
  3.         Dim wp As New WrapPanel
  4.         wp.Background = Brushes.AliceBlue
  5.         Me.Title = "Test WrapPanel"
  6.         Me.Content = wp
  7.         For z As Integer = 0 To 25
  8.             Dim btn As New Button
  9.             btn.Name = "Button" & z
  10.             btn.Content = "Button _" & Chr(&H41 + z)
  11.             btn.VerticalAlignment = Windows.VerticalAlignment.Center
  12.             btn.HorizontalAlignment = Windows.HorizontalAlignment.Center
  13.             AddHandler btn.Click, AddressOf Button_Click
  14.             wp.Children.Add(btn)
  15.         Next
  16.     End Sub
  17.     Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
  18.         MessageBox.Show(CType(e.Source, Button).Content.ToString)
  19.     End Sub
複製代碼
[ 本帖最後由 bauann 於 2008-3-24 20:35 編輯 ]
作者: 路人甲    時間: 2008-3-25 21:38

感謝bauann 大大給我們這麼好的資料,我去msdn看了一下
一些範例,例如,同心圓範例
可惜的是C#,我將之改成為 vb, 有興趣的人研究研究
http://msdn2.microsoft.com/zh-tw/library/ms771460.aspx 為原載點

Xaml code


  1. <Window x:Class="Window1"
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     Title="Concentric Rings" Width="800" Height="512">
  5.     <Canvas Name="MainCanvas" Background="#FFE0E0E0"/>
  6. </Window>
複製代碼
vb code

  1. Option Strict On
  2. Option Explicit On
  3. Imports System
  4. Imports System.Windows
  5. Imports System.Windows.Controls
  6. Imports System.Windows.Data
  7. Imports System.Windows.Documents
  8. Imports System.Windows.Media
  9. Imports System.Windows.Shapes
  10. Imports System.Windows.Media.Animation
  11. Public Class Window1
  12.     Private frameTimer As System.Windows.Threading.DispatcherTimer
  13.     Private rand As Random
  14.     Public Sub New()
  15.         ' 此為 Windows Form 設計工具所需的呼叫。
  16.         InitializeComponent()
  17.         ' 在 InitializeComponent() 呼叫之後加入任何初始設定。
  18.         With Me
  19.             .WindowState = Windows.WindowState.Maximized
  20.             .WindowStyle = Windows.WindowStyle.None
  21.             .ResizeMode = Windows.ResizeMode.NoResize
  22.             .frameTimer = New System.Windows.Threading.DispatcherTimer
  23.             With .frameTimer
  24.                 .Interval = TimeSpan.FromTicks(CType(5 * 10 ^ 6, Long))
  25.                 AddHandler .Tick, AddressOf trOnTick
  26.                 .Start()
  27.             End With
  28.             .rand = New Random(100)
  29.         End With
  30.     End Sub
  31.     Private Sub trOnTick(ByVal sender As Object, ByVal e As EventArgs)
  32.         Me.CreateCircles()
  33.     End Sub
  34.     Private Sub Window1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.KeyDown
  35.         If (e.Key = System.Windows.Input.Key.Escape) Then Me.Close()
  36.     End Sub

  37.     Private Sub CreateCircles()
  38.         Dim centerX As Double = Me.MainCanvas.ActualWidth / 2.0
  39.         Dim centerY As Double = Me.MainCanvas.ActualHeight / 2.0
  40.         Dim myColors() As Color = {Colors.White, Colors.Green, Colors.Green, Colors.Lime}
  41.   
  42.         Dim e As New Ellipse()
  43.         Dim alpha As Byte = CType(rand.Next(96, 192), Byte)
  44.         Dim colorIndex As Int32 = rand.Next(4)
  45.         e.Stroke = New SolidColorBrush(Color.FromArgb(alpha, myColors(colorIndex).R, _
  46.                                             myColors(colorIndex).G, myColors(colorIndex).B))
  47.         e.StrokeThickness = rand.Next(1, 4)
  48.         e.Width = 0.0
  49.         e.Height = 0.0
  50.         Dim offsetX As Double = 16 - rand.Next(32)
  51.         Dim offsetY As Double = 16 - rand.Next(32)
  52.         Me.MainCanvas.Children.Add(e)
  53.         e.SetValue(Canvas.LeftProperty, centerX + offsetX)
  54.         e.SetValue(Canvas.TopProperty, centerY + offsetY)
  55.         Dim duration As Double = 6.0 + 3 * rand.NextDouble()
  56.         Dim delay As Double = 16.0 * rand.NextDouble()
  57.         Dim offsetTransform As TranslateTransform = New TranslateTransform()
  58.         Dim offsetXAnimation As DoubleAnimation = New DoubleAnimation(0.0, -256.0, New Duration(TimeSpan.FromSeconds(duration)))
  59.         offsetXAnimation.BeginTime = TimeSpan.FromSeconds(delay)
  60.         offsetTransform.BeginAnimation(TranslateTransform.XProperty, offsetXAnimation)
  61.         offsetTransform.BeginAnimation(TranslateTransform.YProperty, offsetXAnimation)
  62.         e.RenderTransform = offsetTransform

  63.         Dim SizeAnimation As DoubleAnimation = New DoubleAnimation(0.0, 512.0, New Duration(TimeSpan.FromSeconds(duration)))
  64.         SizeAnimation.BeginTime = TimeSpan.FromSeconds(delay)
  65.         e.BeginAnimation(Ellipse.WidthProperty, SizeAnimation)
  66.         e.BeginAnimation(Ellipse.HeightProperty, SizeAnimation)
  67.         Dim opacityAnimation As DoubleAnimation = New DoubleAnimation(duration - 1.0, 0.0, New Duration(TimeSpan.FromSeconds(duration)))
  68.         opacityAnimation.BeginTime = TimeSpan.FromSeconds(delay)
  69.         e.BeginAnimation(Ellipse.OpacityProperty, opacityAnimation)
  70.     End Sub

  71. End Class
複製代碼

作者: 路人甲    時間: 2008-3-26 08:46

  1. Option Strict On
  2. Option Explicit On
  3. Imports System
  4. Imports System.Windows
  5. Imports System.Windows.Controls
  6. Imports System.Windows.Data
  7. Imports System.Windows.Documents
  8. Imports System.Windows.Media
  9. Imports System.Windows.Shapes
  10. Imports System.Windows.Media.Animation
  11. Public Class Window1
  12. Private rand As Random
  13. Public Sub New()
  14. ' 此為 Windows Form 設計工具所需的呼叫。
  15. InitializeComponent()
  16. ' 在 InitializeComponent() 呼叫之後加入任何初始設定。
  17. With Me
  18. .WindowState = Windows.WindowState.Maximized
  19. .WindowStyle = Windows.WindowStyle.None
  20. .ResizeMode = Windows.ResizeMode.NoResize
  21. .rand = New Random(100)
  22. .Show()
  23. End With
  24. Me.CreateCircles()
  25. End Sub
  26. Private Sub Window1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.KeyDown
  27. If (e.Key = System.Windows.Input.Key.Escape) Then Me.Close()
  28. End Sub

  29. Private Sub CreateCircles()
  30. Dim centerX As Double = Me.MainCanvas.ActualWidth / 2.0
  31. Dim centerY As Double = Me.MainCanvas.ActualHeight / 2.0
  32. Dim myColors() As Color = {Colors.White, Colors.Green, Colors.Green, Colors.Lime}

  33. For i As Int32 = 0 To 20
  34. Dim e As New Ellipse()
  35. Dim alpha As Byte = CType(rand.Next(96, 192), Byte)
  36. Dim colorIndex As Int32 = rand.Next(4)
  37. e.Stroke = New SolidColorBrush(Color.FromArgb(alpha, myColors(colorIndex).R, _
  38. myColors(colorIndex).G, myColors(colorIndex).B))
  39. e.StrokeThickness = rand.Next(1, 4)
  40. e.Width = 0.0
  41. e.Height = 0.0
  42. Dim offsetX As Double = 16 - rand.Next(32)
  43. Dim offsetY As Double = 16 - rand.Next(32)
  44. Me.MainCanvas.Children.Add(e)
  45. e.SetValue(Canvas.LeftProperty, centerX + offsetX)
  46. e.SetValue(Canvas.TopProperty, centerY + offsetY)
  47. Dim duration As Double = 6.0 + 3 * rand.NextDouble()
  48. Dim delay As Double = 16.0 * rand.NextDouble()
  49. Dim offsetTransform As TranslateTransform = New TranslateTransform()
  50. Dim offsetXAnimation As DoubleAnimation = New DoubleAnimation(0.0, -256.0, New Duration(TimeSpan.FromSeconds(duration)))
  51. offsetXAnimation.RepeatBehavior = RepeatBehavior.Forever

  52. offsetXAnimation.BeginTime = TimeSpan.FromSeconds(delay)
  53. offsetTransform.BeginAnimation(TranslateTransform.XProperty, offsetXAnimation)
  54. offsetTransform.BeginAnimation(TranslateTransform.YProperty, offsetXAnimation)
  55. e.RenderTransform = offsetTransform

  56. Dim SizeAnimation As DoubleAnimation = New DoubleAnimation(0.0, 512.0, New Duration(TimeSpan.FromSeconds(duration)))
  57. SizeAnimation.RepeatBehavior = RepeatBehavior.Forever

  58. SizeAnimation.BeginTime = TimeSpan.FromSeconds(delay)
  59. e.BeginAnimation(Ellipse.WidthProperty, SizeAnimation)
  60. e.BeginAnimation(Ellipse.HeightProperty, SizeAnimation)
  61. Dim opacityAnimation As DoubleAnimation = New DoubleAnimation(duration - 1.0, 0.0, New Duration(TimeSpan.FromSeconds(duration)))
  62. opacityAnimation.BeginTime = TimeSpan.FromSeconds(delay)
  63. opacityAnimation.RepeatBehavior = RepeatBehavior.Forever

  64. e.BeginAnimation(Ellipse.OpacityProperty, opacityAnimation)
  65. Next i
  66. End Sub

  67. End Class
複製代碼
或許MSDN減少更動比較好,感覺上效能較好
不過,我的電腦經此一測試後,感覺應要換了吧
家中的電腦  amd 1ghz 的跑起來 圓畫多的時候 CPU使用率 100% 還卡卡的跑不太動
拿到公司一測
INTEL CORE 2 DUO E6750 2.66GHZ,  跑起來 CPU 使用率只有1x%到3x%
怎麼差這麼多,電腦要拿去丟掉了
作者: 路人甲    時間: 2008-3-26 23:54

http://msdn2.microsoft.com/zh-tw/library/ms771362.aspx
此為計算機範例
我仍然再將之翻譯為vb
首先我們仍有 Xaml code

  1. <Window x:Class="Window1"
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     Title="WPF Calculator"
  5.     Height="400"
  6.     Width="600"
  7.     ResizeMode="CanMinimize"  
  8.         Icon="AppIcon.ico"
  9.     TextInput="OnWindowKeyDown" Name="Window1">

  10.     <DockPanel Name="MyPanel">
  11.         <Menu  DockPanel.Dock="Top" Height="26">
  12.             <MenuItem Header="File" Name="MenuItem1">
  13.                 <MenuItem Click="OnMenuExit" Header="Exit"/>
  14.             </MenuItem>
  15.             <MenuItem Header="View" Name="MenuItem2">
  16.                 <MenuItem Name="StandardMenu" Click="OnMenuStandard" IsCheckable="true" IsChecked="True" Header="Standard"/>
  17.             </MenuItem>
  18.             <MenuItem Header="Help" Name="MenuItem3">
  19.                 <MenuItem  Click="OnMenuAbout" Header="About"/>
  20.             </MenuItem>
  21.         </Menu>
  22.         <Grid Name="MyGrid" Background="Wheat"  ShowGridLines="False">
  23.             <Grid.Resources >
  24.                 <Storyboard x:Key="playStoryboard">
  25.                     <DoubleAnimation From="50"  To="40" Duration="0:0:0.25" RepeatBehavior="1x" AutoReverse="True" Storyboard.TargetName="TB" Storyboard.TargetProperty="(Ellipse.Height)"/>
  26.                     <DoubleAnimation From="50"  To="44" Duration="0:0:0.25" RepeatBehavior="1x" AutoReverse="True" Storyboard.TargetName="TB" Storyboard.TargetProperty="(Ellipse.Width)"/>
  27.                 </Storyboard>
  28.                 <Style x:Key="DigitBtn"  TargetType="{x:Type Button}">
  29.                     <Setter Property="Focusable" Value="False"/>
  30.                     <Setter Property="FontSize" Value="14pt"/>
  31.                     <Setter Property="Margin" Value="0"/>
  32.                     <Setter Property="Template">
  33.                         <Setter.Value>
  34.                             <ControlTemplate TargetType="{x:Type Button}">
  35.                                 <Grid Width="60" Height="50">
  36.                                     <Ellipse Width="57" Height="49" x:Name="TB"  StrokeThickness="1"
  37.                            Stroke="{TemplateBinding Foreground}" Fill="{TemplateBinding Background}"
  38.                            HorizontalAlignment="Center" VerticalAlignment="Center" />
  39.                                     <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center"
  40.                     VerticalAlignment="Center"/>
  41.                                 </Grid>
  42.                                 <ControlTemplate.Triggers>
  43.                                     <Trigger Property="IsMouseOver" Value="true">
  44.                                         <Setter TargetName="TB" Property="Ellipse.Fill" Value="Lightblue" />
  45.                                     </Trigger>
  46.                                     <Trigger Property="IsPressed" Value="true">
  47.                                         <Setter TargetName="TB" Property="Ellipse.Fill" Value="Blue" />
  48.                                     </Trigger>

  49.                                     <EventTrigger RoutedEvent="ButtonBase.Click">
  50.                                         <EventTrigger.Actions>
  51.                                             <BeginStoryboard Name="playStoryboard" Storyboard="{StaticResource playStoryboard}"/>
  52.                                         </EventTrigger.Actions>
  53.                                     </EventTrigger>
  54.                                 </ControlTemplate.Triggers>
  55.                             </ControlTemplate>
  56.                         </Setter.Value>
  57.                     </Setter>
  58.                 </Style>
  59.             </Grid.Resources>
  60.             <Grid.ColumnDefinitions>
  61.                 <ColumnDefinition/>
  62.                 <ColumnDefinition/>
  63.                 <ColumnDefinition/>
  64.                 <ColumnDefinition/>
  65.                 <ColumnDefinition/>
  66.                 <ColumnDefinition/>
  67.                 <ColumnDefinition/>
  68.                 <ColumnDefinition/>
  69.                 <ColumnDefinition/>
  70.             </Grid.ColumnDefinitions>
  71.             <Grid.RowDefinitions>
  72.                 <RowDefinition Height="56*" />
  73.                 <RowDefinition Height="56*" />
  74.                 <RowDefinition Height="56*" />
  75.                 <RowDefinition Height="56*" />
  76.                 <RowDefinition Height="40*" />
  77.                 <RowDefinition Height="16*" />
  78.                 <RowDefinition Height="56*" />
  79.             </Grid.RowDefinitions>
  80.             <Button Name="B7" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="4" Grid.Row="2">7</Button>
  81.             <Button Name="B8" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="5" Grid.Row="2">8</Button>
  82.             <Button Name="B9" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="6" Grid.Row="2">9</Button>
  83.             <Button Name="B4" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="4" Grid.Row="3" >4</Button>
  84.             <Button Name="B5" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="5" Grid.Row="3" >5</Button>
  85.             <Button Name="B6" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="6" Grid.Row="3" >6</Button>

  86.             <Button Name="B1" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="4" Grid.Row="4" Grid.RowSpan="2">1</Button>
  87.             <Button Name="B2" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="5" Grid.Row="4" Grid.RowSpan="2">2</Button>
  88.             <Button Name="B3" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="6" Grid.Row="4" Grid.RowSpan="2">3</Button>
  89.             <Button Name="B0" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="4" Grid.Row="6" >0</Button>
  90.             <Button Name="BPeriod" Click="DigitBtn_Click" Style="{StaticResource DigitBtn}" Grid.Column="5" Grid.Row="6" >.</Button>
  91.             <Button Name="BPM"        Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="6" Grid.Row="6" >+/-</Button>
  92.             <Button Name="BDevide"    Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}" Grid.Column="7" Grid.Row="2" >/</Button>
  93.             <Button Name="BMultiply"  Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="7" Grid.Row="3" >*</Button>
  94.             <Button Name="BMinus"  Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="7" Grid.Row="4" Grid.RowSpan="2">-</Button>
  95.             <Button Name="BPlus"      Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="7" Grid.Row="6" >+</Button>

  96.             <Button Name="BSqrt"    Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="8" Grid.Row="2"   ToolTip="Usage: 'A Sqrt'" >Sqrt</Button>
  97.             <Button Name="BPercent"   Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="8" Grid.Row="3"   ToolTip="Usage: 'A % B ='" >%</Button>
  98.             <Button Name="BOneOver"   Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="8" Grid.Row="4"   ToolTip="Usage: 'A 1/X'" Grid.RowSpan="2">1/X</Button>
  99.             <Button Name="BEqual"   Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="8" Grid.Row="6" >=</Button>

  100.             <Button Name="BC"  Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="8" Grid.Row="1" Grid.ColumnSpan="1" ToolTip="Clear All">C</Button>
  101.             <Button Name="BCE" Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="7" Grid.Row="1" Grid.ColumnSpan="1"  ToolTip="Clear Current Entry">CE</Button>

  102.             <Button Name="BMemClear"    Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="3" Grid.Row="2"  ToolTip="Clear Memory" >MC</Button>
  103.             <Button Name="BMemRecall"   Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="3" Grid.Row="3"  ToolTip="Recall Memory">MR</Button>
  104.             <Button Name="BMemSave"    Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="3" Grid.Row="4"  ToolTip="Store in Memory" Grid.RowSpan="2">MS</Button>
  105.             <Button Name="BMemPlus"    Click="OperBtn_Click" Background="Darkgray" Style="{StaticResource DigitBtn}"  Grid.Column="3" Grid.Row="6"  ToolTip="Add To Memory">M+</Button>
  106.             <TextBlock  Name="BMemBox" Grid.Column="3" Grid.Row="1" Margin="10,17,10,17" Grid.ColumnSpan="2">Memory: [empty]</TextBlock>
  107.         </Grid>
  108.     </DockPanel>
  109. </Window>

複製代碼
然後記得將appicon.ico這個小圖檔給加入專案,並要把建置動作變為Resource

再來新增一個 類別庫檔名為MyTextBox.vb
並在其中加入程式碼
  1. Imports System
  2. Imports System.Collections.Generic
  3. Imports System.Text
  4. Imports System.Windows.Input

  5. Class MyTextBox
  6. Inherits TextBox
  7. Protected Overrides Sub OnPreviewGotKeyboardFocus(ByVal e As System.Windows.Input.KeyboardFocusChangedEventArgs)
  8. e.Handled = True
  9. MyBase.OnPreviewGotKeyboardFocus(e)
  10. End Sub
  11. End Class
複製代碼
最後仍是我們的主要程式碼在window1中


  1. Option Strict On
  2. Option Explicit On

  3. Imports System
  4. Imports System.Windows
  5. Imports System.Windows.Controls
  6. Imports System.Windows.Data
  7. Imports System.Windows.Documents
  8. Imports System.Windows.Media
  9. Imports System.Windows.Shapes
  10. Imports System.Windows.Media.Animation

  11. Public Class Window1


  12. Shared DisplayBox As MyTextBox
  13. Shared PaperBox As MyTextBox
  14. Shared Paper As PaperTrail

  15. Private LastOper As Operation

  16. Public Sub New()

  17. ' 此為 Windows Form 設計工具所需的呼叫。
  18. InitializeComponent()

  19. ' 在 InitializeComponent() 呼叫之後加入任何初始設定。
  20. DisplayBox = New MyTextBox()
  21. Grid.SetRow(DisplayBox, 0)
  22. Grid.SetColumn(DisplayBox, 0)
  23. Grid.SetColumnSpan(DisplayBox, 9)

  24. DisplayBox.Height = 30
  25. MyGrid.Children.Add(DisplayBox)

  26. PaperBox = New MyTextBox()
  27. Grid.SetRow(PaperBox, 1)
  28. Grid.SetColumn(PaperBox, 0)
  29. Grid.SetColumnSpan(PaperBox, 3)
  30. Grid.SetRowSpan(PaperBox, 5)
  31. PaperBox.IsReadOnly = True
  32. PaperBox.VerticalScrollBarVisibility = ScrollBarVisibility.Visible
  33. PaperBox.Margin = New Thickness(3.0, 1.0, 1.0, 1.0)
  34. PaperBox.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto

  35. Paper = New PaperTrail()

  36. MyGrid.Children.Add(PaperBox)
  37. ProcessKey("0"c)
  38. EraseDisplay = True


  39. End Sub

  40. Private Enum Operation

  41. None
  42. Devide
  43. Multiply
  44. Subtract
  45. Add
  46. Percent
  47. Sqrt
  48. OneX
  49. Negate
  50. End Enum


  51. Private _erasediplay As Boolean
  52. Private Property EraseDisplay() As Boolean
  53. Get
  54. Return _erasediplay
  55. End Get
  56. Set(ByVal value As Boolean)
  57. _erasediplay = value
  58. End Set
  59. End Property

  60. Private _mem_val As String
  61. Private Property Memory() As Double
  62. Get
  63. If (_mem_val = String.Empty) Then
  64. Return 0.0
  65. Else
  66. Return Convert.ToDouble(_mem_val)
  67. End If
  68. End Get
  69. Set(ByVal value As Double)
  70. _mem_val = value.ToString()
  71. End Set
  72. End Property
  73. Private _last_val As String
  74. Private Property LastValue() As String
  75. Get
  76. If (_last_val = String.Empty) Then Return "0"

  77. Return _last_val

  78. End Get
  79. Set(ByVal value As String)
  80. _last_val = value
  81. End Set
  82. End Property

  83. Private _display As String
  84. Private Property Display() As String
  85. Get
  86. Return _display
  87. End Get
  88. Set(ByVal value As String)
  89. _display = value
  90. End Set
  91. End Property

  92. Private Sub OnWindowKeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.TextCompositionEventArgs)

  93. Dim s As String = e.Text
  94. Dim c As Char = (s.ToCharArray)(0)
  95. e.Handled = True

  96. If ((AscW(c) >= AscW("0"c) AndAlso AscW(c) <= AscW("9"c)) OrElse c = "."c OrElse c = vbBack) Then

  97. ProcessKey(c)
  98. Return
  99. End If

  100. Select Case (c)

  101. Case "+"c
  102. ProcessOperation("BPlus")
  103. Case "-"c
  104. ProcessOperation("BMinus")
  105. Case "*"c
  106. ProcessOperation("BMultiply")
  107. Case "/"c
  108. ProcessOperation("BDevide")
  109. Case "%"c
  110. ProcessOperation("BPercent")
  111. Case "="c
  112. ProcessOperation("BEqual")

  113. End Select

  114. End Sub

  115. Private Sub DigitBtn_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

  116. Dim s As String = (DirectCast(sender, Button)).Content.ToString()


  117. Dim ids() As Char = s.ToCharArray()
  118. ProcessKey(ids(0))
  119. End Sub



  120. Private Sub ProcessKey(ByVal c As Char)
  121. If (EraseDisplay) Then
  122. Display = String.Empty
  123. EraseDisplay = False
  124. End If

  125. AddToDisplay(c)

  126. End Sub

  127. Private Sub ProcessOperation(ByVal s As String)

  128. Dim d As Double = 0.0

  129. Select Case s

  130. Case "BPM"
  131. LastOper = Operation.Negate
  132. LastValue = Display
  133. CalcResults()
  134. LastValue = Display
  135. EraseDisplay = True
  136. LastOper = Operation.None
  137. Case "BDevide"

  138. If (EraseDisplay) Then 'stil wait for a digit...
  139. 'stil wait for a digit...
  140. LastOper = Operation.Devide
  141. Else
  142. CalcResults()
  143. LastOper = Operation.Devide
  144. LastValue = Display
  145. EraseDisplay = True
  146. End If

  147. Case "BMultiply"

  148. If (EraseDisplay) Then 'stil wait for a digit...
  149. LastOper = Operation.Multiply
  150. Else
  151. CalcResults()
  152. LastOper = Operation.Multiply
  153. LastValue = Display
  154. EraseDisplay = True
  155. End If

  156. Case "BMinus"
  157. If (EraseDisplay) Then 'stil wait for a digit...
  158. LastOper = Operation.Subtract
  159. Else
  160. CalcResults()
  161. LastOper = Operation.Subtract
  162. LastValue = Display
  163. EraseDisplay = True
  164. End If

  165. Case "BPlus"
  166. If (EraseDisplay) Then
  167. 'stil wait for a digit...
  168. LastOper = Operation.Add
  169. Else
  170. CalcResults()
  171. LastOper = Operation.Add
  172. LastValue = Display
  173. EraseDisplay = True
  174. End If
  175. Case "BEqual"
  176. If Not (EraseDisplay) Then 'stil wait for a digit...
  177. CalcResults()
  178. EraseDisplay = True
  179. LastOper = Operation.None
  180. LastValue = Display
  181. 'val = Display
  182. End If

  183. Case "BSqrt"
  184. LastOper = Operation.Sqrt
  185. LastValue = Display
  186. CalcResults()
  187. LastValue = Display
  188. EraseDisplay = True
  189. LastOper = Operation.None
  190. Case "BPercent"
  191. If (EraseDisplay) Then 'stil wait for a digit...
  192. LastOper = Operation.Percent
  193. Else
  194. CalcResults()
  195. LastOper = Operation.Percent
  196. LastValue = Display
  197. EraseDisplay = True
  198. 'LastOper = Operation.None
  199. End If
  200. Case "BOneOver"
  201. LastOper = Operation.OneX
  202. LastValue = Display
  203. CalcResults()
  204. LastValue = Display
  205. EraseDisplay = True
  206. LastOper = Operation.None

  207. Case "BC" 'clear All
  208. LastOper = Operation.None
  209. LastValue = String.Empty

  210. Display = LastValue
  211. Paper.Clear()
  212. UpdateDisplay()
  213. Case "BCE" 'clear entry
  214. LastOper = Operation.None
  215. Display = LastValue
  216. UpdateDisplay()
  217. Case "BMemClear"
  218. Memory = 0.0F
  219. DisplayMemory()
  220. Case "BMemSave"
  221. Memory = Convert.ToDouble(Display)
  222. DisplayMemory()
  223. EraseDisplay = True
  224. Case "BMemRecall"
  225. Display = Memory.ToString()
  226. UpdateDisplay()
  227. EraseDisplay = False
  228. Case "BMemPlus"
  229. d = Memory + Convert.ToDouble(Display)
  230. Memory = d
  231. DisplayMemory()
  232. EraseDisplay = True
  233. End Select



  234. End Sub

  235. Private Sub OperBtn_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

  236. ProcessOperation(DirectCast(sender, Button).Name.ToString)
  237. End Sub


  238. Private Function Calc(ByVal LastOper As Operation) As Double

  239. Dim d As Double = 0.0


  240. Try

  241. Select Case (LastOper)

  242. Case Operation.Devide
  243. Paper.AddArguments(LastValue + " / " + Display)
  244. d = (Convert.ToDouble(LastValue) / Convert.ToDouble(Display))
  245. CheckResult(d)
  246. Paper.AddResult(d.ToString())

  247. Case Operation.Add
  248. Paper.AddArguments(LastValue + " + " + Display)
  249. d = Convert.ToDouble(LastValue) + Convert.ToDouble(Display)
  250. CheckResult(d)
  251. Paper.AddResult(d.ToString())

  252. Case Operation.Multiply
  253. Paper.AddArguments(LastValue + " * " + Display)
  254. d = Convert.ToDouble(LastValue) * Convert.ToDouble(Display)
  255. CheckResult(d)
  256. Paper.AddResult(d.ToString())

  257. Case Operation.Percent
  258. 'Note: this is different (but make more sense) then Windows calculator
  259. Paper.AddArguments(LastValue + " % " + Display)
  260. d = (Convert.ToDouble(LastValue) * Convert.ToDouble(Display)) / 100.0F
  261. CheckResult(d)
  262. Paper.AddResult(d.ToString())

  263. Case Operation.Subtract
  264. Paper.AddArguments(LastValue + " - " + Display)
  265. d = Convert.ToDouble(LastValue) - Convert.ToDouble(Display)
  266. CheckResult(d)
  267. Paper.AddResult(d.ToString())

  268. Case Operation.Sqrt
  269. Paper.AddArguments("Sqrt( " + LastValue + " )")
  270. d = Math.Sqrt(Convert.ToDouble(LastValue))
  271. CheckResult(d)
  272. Paper.AddResult(d.ToString())

  273. Case Operation.OneX
  274. Paper.AddArguments("1 / " + LastValue)
  275. d = 1.0F / Convert.ToDouble(LastValue)
  276. CheckResult(d)
  277. Paper.AddResult(d.ToString())

  278. Case Operation.Negate
  279. d = Convert.ToDouble(LastValue) * (-1.0F)

  280. End Select

  281. Catch
  282. d = 0
  283. Dim parent As Window = DirectCast(MyPanel.Parent, Window)
  284. Paper.AddResult("Error")
  285. MessageBox.Show(Parent, "Operation cannot be perfomed", Parent.Title)
  286. End Try

  287. Return d
  288. End Function

  289. Private Sub CheckResult(ByVal d As Double)

  290. If (Double.IsNegativeInfinity(d) OrElse Double.IsPositiveInfinity(d) OrElse Double.IsNaN(d)) Then
  291. Throw New Exception("Illegal value")
  292. End If

  293. End Sub

  294. Private Sub DisplayMemory()

  295. If (_mem_val <> String.Empty) Then
  296. BMemBox.Text = "Memory: " + _mem_val
  297. Else
  298. BMemBox.Text = "Memory: [empty]"
  299. End If
  300. End Sub

  301. Private Sub CalcResults()

  302. Dim d As Double
  303. If (LastOper = Operation.None) Then Return

  304. d = Calc(LastOper)
  305. Display = d.ToString()

  306. UpdateDisplay()
  307. End Sub

  308. Private Sub UpdateDisplay()

  309. If (Display = String.Empty) Then
  310. DisplayBox.Text = "0"
  311. Else
  312. DisplayBox.Text = Display
  313. End If
  314. End Sub



  315. Private Sub AddToDisplay(ByVal c As Char)

  316. If (c = "."c) Then

  317. If (Display.IndexOf("."c, 0) >= 0) Then Return 'already exists

  318. Display = Display + c

  319. Else

  320. If (AscW(c) >= AscW("0"c) AndAlso AscW(c) <= AscW("9"c)) Then
  321. Display = Display + c

  322. Else
  323. If (c = vbBack) Then 'backspace ?

  324. If (Display.Length <= 1) Then
  325. Display = String.Empty
  326. Else

  327. Dim i As Int32 = Display.Length
  328. Display = Display.Remove(i - 1, 1) 'remove last char
  329. End If
  330. End If
  331. End If
  332. End If

  333. UpdateDisplay()
  334. End Sub

  335. Sub OnMenuAbout(ByVal sender As Object, ByVal e As RoutedEventArgs)

  336. Dim parent As Window = DirectCast(MyPanel.Parent, Window)
  337. MessageBox.Show(Parent, Parent.Title + " - By Jossef Goldberg ", Parent.Title, MessageBoxButton.OK, MessageBoxImage.Information)

  338. End Sub

  339. Sub OnMenuExit(ByVal sender As Object, ByVal e As RoutedEventArgs)

  340. Me.Close()
  341. End Sub
  342. Sub OnMenuStandard(ByVal sender As Object, ByVal e As RoutedEventArgs)

  343. DirectCast(StandardMenu, MenuItem).IsChecked = True 'for now always Standard
  344. End Sub
  345. Sub OnMenuScientific(ByVal sender As Object, ByVal e As RoutedEventArgs)

  346. '((MenuItem)StandardMenu).IsChecked = false
  347. End Sub

  348. Private Class PaperTrail

  349. Private args As String

  350. Public Sub AddArguments(ByVal a As String)

  351. args = a
  352. End Sub

  353. Public Sub AddResult(ByVal r As String)
  354. PaperBox.Text += args + " = " + r + vbNewLine
  355. End Sub

  356. Public Sub Clear()
  357. PaperBox.Text = String.Empty
  358. args = String.Empty
  359. End Sub
  360. End Class


  361. End Class
複製代碼
[ 本帖最後由 路人甲 於 2008-3-26 23:57 編輯 ]
作者: 路人甲    時間: 2008-3-27 21:14

http://msdn2.microsoft.com/zh-tw/library/ms771572.aspx
範例檔為上面的網址,一樣修改為 vb
請記得一定要加入下載後的資源檔到專案中
這次是 webbrowser application
所以請先新增 WpfBrowserApplication
而compile完後請點擊副檔名為 xbap 之檔案
以下為 Xaml code

  1. <Page  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     xmlns:my="clr-namespace"
  5.     x:Class="Page1"
  6.     Title="3D Cube Animation Demo"
  7.     Loaded="OnLoaded"
  8.     >
  9.     <Page.Resources>
  10.         <Storyboard x:Key="RotateStoryboard">
  11.             <ParallelTimeline RepeatBehavior="Forever"  Storyboard.TargetName="myRotate" Storyboard.TargetProperty="Angle" >
  12.                 <DoubleAnimation From="0" To="360" Duration="0:0:30"/>
  13.             </ParallelTimeline>
  14.         </Storyboard>
  15.         <MeshGeometry3D x:Key="PlaneMesh"
  16.             Positions="-1 -1 0  1 -1 0  -1 1 0  1 1 0"
  17.             Normals="0 0 1  0 0 1  0 0 1  0 0 1"
  18.             TextureCoordinates="0 1  1 1  0 0  1 0   "
  19.             TriangleIndices="0 1 2  1 3 2" />

  20.         <MeshGeometry3D x:Key="CubeMesh"
  21.    TriangleIndices="0,1,2 3,4,5 6,7,8 9,10,11 12,13,14 15,16,17 18,19,20 21,22,23 24,25,26 27,28,29 30,31,32 33,34,35 "
  22.    Normals="0,0,-1 0,0,-1 0,0,-1 0,0,-1 0,0,-1 0,0,-1 0,0,1 0,0,1 0,0,1 0,0,1 0,0,1 0,0,1 0,-1,0 0,-1,0 0,-1,0 0,-1,0 0,-1,0 0,-1,0 1,0,0 1,0,0 1,0,0 1,0,0 1,0,0 1,0,0 0,1,0 0,1,0 0,1,0 0,1,0 0,1,0 0,1,0 -1,0,0 -1,0,0 -1,0,0 -1,0,0 -1,0,0 -1,0,0 "
  23.    TextureCoordinates="1,0 1,1 0,1 0,1 0,0 1,0 0,0 1,0 1,1 1,1 0,1 0,0 0,0 1,0 1,1 1,1 0,1 0,0 1,0 1,1 0,1 0,1 0,0 1,0 1,1 0,1 0,0 0,0 1,0 1,1 0,1 0,0 1,0 1,0 1,1 0,1 "
  24.    Positions="-0.5,-0.5,-0.5 -0.5,0.5,-0.5 0.5,0.5,-0.5 0.5,0.5,-0.5 0.5,-0.5,-0.5 -0.5,-0.5,-0.5 -0.5,-0.5,0.5 0.5,-0.5,0.5 0.5,0.5,0.5 0.5,0.5,0.5 -0.5,0.5,0.5 -0.5,-0.5,0.5 -0.5,-0.5,-0.5 0.5,-0.5,-0.5 0.5,-0.5,0.5 0.5,-0.5,0.5 -0.5,-0.5,0.5 -0.5,-0.5,-0.5 0.5,-0.5,-0.5 0.5,0.5,-0.5 0.5,0.5,0.5 0.5,0.5,0.5 0.5,-0.5,0.5 0.5,-0.5,-0.5 0.5,0.5,-0.5 -0.5,0.5,-0.5 -0.5,0.5,0.5 -0.5,0.5,0.5 0.5,0.5,0.5 0.5,0.5,-0.5 -0.5,0.5,-0.5 -0.5,-0.5,-0.5 -0.5,-0.5,0.5 -0.5,-0.5,0.5 -0.5,0.5,0.5 -0.5,0.5,-0.5 "
  25.   />
  26.         <MeshGeometry3D x:Key="CubeInvertedMesh"
  27.    TriangleIndices="0,1,2 3,4,5 6,7,8 9,10,11 12,13,14 15,16,17 18,19,20 21,22,23 24,25,26 27,28,29 30,31,32 33,34,35 "
  28.    Normals="0,0,1 0,0,1 0,0,1 0,0,1 0,0,1 0,0,1 0,0,-1 0,0,-1 0,0,-1 0,0,-1 0,0,-1 0,0,-1 0,1,0 0,1,0 0,1,0 0,1,0 0,1,0 0,1,0 -1,0,0 -1,0,0 -1,0,0 -1,0,0 -1,0,0 -1,0,0 0,-1,0 0,-1,0 0,-1,0 0,-1,0 0,-1,0 0,-1,0 1,0,0 1,0,0 1,0,0 1,0,0 1,0,0 1,0,0 "
  29.    TextureCoordinates="0,1 1,1 1,0 1,0 0,0 0,1 1,1 1,0 0,0 0,0 0,1 1,1 1,1 1,0 0,0 0,0 0,1 1,1 0,1 1,1 1,0 1,0 0,0 0,1 0,0 0,1 1,1 1,1 1,0 0,0 1,0 0,0 0,1 0,1 1,1 1,0 "
  30.    Positions="0.5,0.5,-0.5 -0.5,0.5,-0.5 -0.5,-0.5,-0.5 -0.5,-0.5,-0.5 0.5,-0.5,-0.5 0.5,0.5,-0.5 0.5,0.5,0.5 0.5,-0.5,0.5 -0.5,-0.5,0.5 -0.5,-0.5,0.5 -0.5,0.5,0.5 0.5,0.5,0.5 0.5,-0.5,0.5 0.5,-0.5,-0.5 -0.5,-0.5,-0.5 -0.5,-0.5,-0.5 -0.5,-0.5,0.5 0.5,-0.5,0.5 0.5,0.5,0.5 0.5,0.5,-0.5 0.5,-0.5,-0.5 0.5,-0.5,-0.5 0.5,-0.5,0.5 0.5,0.5,0.5 -0.5,0.5,0.5 -0.5,0.5,-0.5 0.5,0.5,-0.5 0.5,0.5,-0.5 0.5,0.5,0.5 -0.5,0.5,0.5 -0.5,-0.5,0.5 -0.5,-0.5,-0.5 -0.5,0.5,-0.5 -0.5,0.5,-0.5 -0.5,0.5,0.5 -0.5,-0.5,0.5 "
  31.   />

  32.         <Transform3DGroup x:Key="CubeMeshTransform">
  33.             <Transform3DGroup.Children>
  34.                 <ScaleTransform3D ScaleX="10" ScaleY="10" ScaleZ="10" />
  35.             </Transform3DGroup.Children>
  36.         </Transform3DGroup>
  37.         <Transform3DGroup x:Key="CubeMeshTransform2">
  38.             <Transform3DGroup.Children>
  39.                 <ScaleTransform3D ScaleX="12" ScaleY="12" ScaleZ="12" />
  40.             </Transform3DGroup.Children>
  41.         </Transform3DGroup>
  42.     </Page.Resources>
  43.     <Grid Background="maroon"  >
  44.         <Grid.ColumnDefinitions>
  45.             <ColumnDefinition Width="100"/>
  46.             <ColumnDefinition Width="*" />
  47.         </Grid.ColumnDefinitions>
  48.         <StackPanel>
  49.             <Button Click="OnImage1Animate" Height="50" Grid.Column="0" Grid.Row="0">Image 1 animate</Button>
  50.         </StackPanel>
  51.         <Viewport3D Focusable="true" Name="myViewport3D" ClipToBounds="true" Grid.Column="1" Grid.Row="0" >
  52.             <Viewport3D.Camera>
  53.                 <PerspectiveCamera
  54.     Position="0,0,3.0"
  55.     LookDirection="0,0,-1"
  56.     UpDirection="0,1,0"
  57.     NearPlaneDistance="0.25"
  58.     FarPlaneDistance="20"
  59.     FieldOfView="60" />
  60.             </Viewport3D.Camera>

  61.             <ModelVisual3D>
  62.                 <ModelVisual3D.Transform>
  63.                     <Transform3DGroup>
  64.                         <Transform3DGroup.Children>
  65.                             <Transform3DCollection >
  66.                                 <ScaleTransform3D ScaleX="1" ScaleY="1"  ScaleZ="1" />
  67.                                 <RotateTransform3D>
  68.                                     <RotateTransform3D.Rotation>
  69.                                         <AxisAngleRotation3D Axis="0 1 0" Angle="0" />
  70.                                     </RotateTransform3D.Rotation>
  71.                                 </RotateTransform3D>
  72.                                 <TranslateTransform3D OffsetX="0" OffsetY="0" OffsetZ="0" />
  73.                             </Transform3DCollection>
  74.                         </Transform3DGroup.Children>
  75.                     </Transform3DGroup>
  76.                 </ModelVisual3D.Transform>
  77.                 <ModelVisual3D.Content>
  78.                     <Model3DGroup >
  79.                         <Model3DGroup.Transform>
  80.                             <Transform3DGroup>
  81.                                 <Transform3DGroup.Children>
  82.                                     <Transform3DCollection >
  83.                                         <ScaleTransform3D ScaleX="0.1" ScaleY="0.1"  ScaleZ="0.1" />
  84.                                         <RotateTransform3D>
  85.                                             <RotateTransform3D.Rotation>
  86.                                                 <AxisAngleRotation3D Axis="0 1 0" Angle="0" />
  87.                                             </RotateTransform3D.Rotation>
  88.                                         </RotateTransform3D>
  89.                                         <TranslateTransform3D OffsetX="0" OffsetY="0" OffsetZ="0" />
  90.                                     </Transform3DCollection>
  91.                                 </Transform3DGroup.Children>
  92.                             </Transform3DGroup>
  93.                         </Model3DGroup.Transform>
  94.                         <Model3DGroup.Children>
  95.                             <!-- Group Child 0 -->
  96.                             <Model3DGroup >
  97.                                 <Model3DGroup.Transform>
  98.                                     <Transform3DGroup>
  99.                                         <Transform3DGroup.Children>
  100.                                             <Transform3DCollection >
  101.                                                 <ScaleTransform3D ScaleX="1" ScaleY="1"  ScaleZ="1" />
  102.                                                 <RotateTransform3D >
  103.                                                     <RotateTransform3D.Rotation >
  104.                                                         <AxisAngleRotation3D x:Name="myRotate" Axis="1 0 0" Angle="0" />
  105.                                                     </RotateTransform3D.Rotation>
  106.                                                 </RotateTransform3D>
  107.                                                 <TranslateTransform3D OffsetX="0" OffsetY="0" OffsetZ="0" />
  108.                                             </Transform3DCollection>
  109.                                         </Transform3DGroup.Children>
  110.                                     </Transform3DGroup>
  111.                                 </Model3DGroup.Transform>
  112.                                 <Model3DGroup.Children>
  113.                                     <!-- Child 0 -->
  114.                                     <GeometryModel3D Transform="{StaticResource CubeMeshTransform}" Geometry="{StaticResource CubeMesh}" >
  115.                                         <GeometryModel3D.Material>
  116.                                             <MaterialGroup>
  117.                                                 <MaterialGroup.Children>
  118.                                                     <EmissiveMaterial>
  119.                                                         <EmissiveMaterial.Brush>
  120.                                                             <ImageBrush ImageSource="roundcornersheet.png">
  121.                                                                 <ImageBrush.Transform>
  122.                                                                     <TransformGroup>
  123.                                                                         <TransformGroup.Children>
  124.                                                                             <RotateTransform CenterX="0.5" CenterY="0.5" Angle="0" />
  125.                                                                         </TransformGroup.Children>
  126.                                                                     </TransformGroup>
  127.                                                                 </ImageBrush.Transform>
  128.                                                             </ImageBrush>
  129.                                                         </EmissiveMaterial.Brush>
  130.                                                     </EmissiveMaterial>
  131.                                                 </MaterialGroup.Children>
  132.                                             </MaterialGroup>
  133.                                         </GeometryModel3D.Material>
  134.                                         <GeometryModel3D.BackMaterial>
  135.                                             <MaterialGroup>
  136.                                                 <MaterialGroup.Children>
  137.                                                     <EmissiveMaterial>
  138.                                                         <EmissiveMaterial.Brush>
  139.                                                             <ImageBrush ImageSource="roundcornersheet.png">
  140.                                                                 <ImageBrush.Transform>
  141.                                                                     <TransformGroup>
  142.                                                                         <TransformGroup.Children>
  143.                                                                             <RotateTransform CenterX="0.5" CenterY="0.5" Angle="0" />
  144.                                                                         </TransformGroup.Children>
  145.                                                                     </TransformGroup>
  146.                                                                 </ImageBrush.Transform>
  147.                                                             </ImageBrush>
  148.                                                         </EmissiveMaterial.Brush>
  149.                                                     </EmissiveMaterial>
  150.                                                 </MaterialGroup.Children>
  151.                                             </MaterialGroup>
  152.                                         </GeometryModel3D.BackMaterial>
  153.                                     </GeometryModel3D>
  154.                                     <GeometryModel3D Transform="{StaticResource CubeMeshTransform2}" Geometry="{StaticResource CubeMesh}" >
  155.                                         <GeometryModel3D.Material>
  156.                                             <MaterialGroup>
  157.                                                 <MaterialGroup.Children>
  158.                                                     <EmissiveMaterial>
  159.                                                         <EmissiveMaterial.Brush>
  160.                                                             <ImageBrush ImageSource="roundcornersheet.png">
  161.                                                                 <ImageBrush.Transform>
  162.                                                                     <TransformGroup>
  163.                                                                         <TransformGroup.Children>
  164.                                                                             <RotateTransform CenterX="0.5" CenterY="0.5" Angle="0" />
  165.                                                                         </TransformGroup.Children>
  166.                                                                     </TransformGroup>
  167.                                                                 </ImageBrush.Transform>
  168.                                                             </ImageBrush>
  169.                                                         </EmissiveMaterial.Brush>
  170.                                                     </EmissiveMaterial>
  171.                                                 </MaterialGroup.Children>
  172.                                             </MaterialGroup>
  173.                                         </GeometryModel3D.Material>
  174.                                         <GeometryModel3D.BackMaterial>
  175.                                             <MaterialGroup>
  176.                                                 <MaterialGroup.Children>
  177.                                                     <EmissiveMaterial>
  178.                                                         <EmissiveMaterial.Brush>
  179.                                                             <ImageBrush ImageSource="roundcornersheet.png">
  180.                                                                 <ImageBrush.Transform>
  181.                                                                     <TransformGroup>
  182.                                                                         <TransformGroup.Children>
  183.                                                                             <RotateTransform CenterX="0.5" CenterY="0.5" Angle="0" />
  184.                                                                         </TransformGroup.Children>
  185.                                                                     </TransformGroup>
  186.                                                                 </ImageBrush.Transform>
  187.                                                             </ImageBrush>
  188.                                                         </EmissiveMaterial.Brush>
  189.                                                     </EmissiveMaterial>
  190.                                                 </MaterialGroup.Children>
  191.                                             </MaterialGroup>
  192.                                         </GeometryModel3D.BackMaterial>
  193.                                     </GeometryModel3D>
  194.                                 </Model3DGroup.Children>
  195.                             </Model3DGroup>

  196.                             <Model3DGroup>
  197.                                 <Model3DGroup.Children>
  198.                                     <AmbientLight Color="#ffcccccc"/>
  199.                                     <DirectionalLight Color="LightGray" Direction="-1,-1,-1" />
  200.                                 </Model3DGroup.Children>
  201.                             </Model3DGroup>

  202.                         </Model3DGroup.Children>
  203.                     </Model3DGroup>
  204.                 </ModelVisual3D.Content>
  205.             </ModelVisual3D>

  206.         </Viewport3D>

  207.     </Grid>
  208. </Page>

複製代碼
在專案中新增一個 vb 檔案 名稱為

trackball.vb 並加入程式碼如下


  1. Option Strict On
  2. Option Explicit On

  3. Imports System
  4. Imports System.Collections.Generic
  5. Imports System.Windows
  6. Imports System.Windows.Input
  7. Imports System.Windows.Controls
  8. Imports System.Windows.Media
  9. Imports System.Windows.Media.Media3D

  10. Public Class Trackball
  11.     Public Sub New()
  12.         Dim _translate As Vector3D = New Vector3D(0, 0, 0)
  13.         Dim _translateDelta As Vector3D = New Vector3D(0, 0, 0)
  14.         Reset()
  15.     End Sub
  16.     Private _center As Vector3D
  17.     Private _centered As Boolean
  18.     Private _scale As Double
  19.     Private _translate As Vector3D
  20.     Private _rotation As Quaternion
  21.     Private _slaves As List(Of Viewport3D)
  22.     Private _scaling As Boolean
  23.     Private _scaleDelta As Double         
  24.     Private _rotationDelta As Quaternion
  25.     Private _point As Point
  26.     Private _translateDelta As Vector3D
  27.     Private _rotating As Boolean
  28.     Private _translating As Boolean

  29.     Public Sub Attach(ByVal element As FrameworkElement)

  30.         With element
  31.             AddHandler .MouseMove, AddressOf Me.MouseMoveHandler
  32.             AddHandler .MouseRightButtonDown, AddressOf Me.MouseDownHandler
  33.             AddHandler .MouseRightButtonUp, AddressOf Me.MouseUpHandler
  34.             AddHandler .MouseWheel, AddressOf Me.OnMouseWheel
  35.         End With

  36.     End Sub

  37.     Public Sub Detach(ByVal element As FrameworkElement)

  38.         With element
  39.             RemoveHandler .MouseMove, AddressOf Me.MouseMoveHandler
  40.             RemoveHandler .MouseRightButtonDown, AddressOf Me.MouseDownHandler
  41.             RemoveHandler .MouseRightButtonUp, AddressOf Me.MouseUpHandler
  42.             RemoveHandler .MouseWheel, AddressOf Me.OnMouseWheel
  43.         End With
  44.     End Sub

  45.     Public Property slaves() As List(Of Viewport3D)
  46.         Get
  47.             If (_slaves Is Nothing) Then _slaves = New List(Of Viewport3D)

  48.             Return _slaves
  49.         End Get
  50.         Set(ByVal value As List(Of Viewport3D))
  51.             _slaves = value
  52.         End Set
  53.     End Property
  54.     Private _enabled As Boolean
  55.     Public Property Enabled() As Boolean
  56.         Get
  57.             Return _enabled AndAlso (_slaves IsNot Nothing) AndAlso (_slaves.Count > 0)
  58.         End Get
  59.         Set(ByVal value As Boolean)
  60.             _enabled = value
  61.         End Set
  62.     End Property

  63.     Private Sub UpdateSlaves(ByVal q As Quaternion, ByVal s As Double, ByVal t As Vector3D)

  64.         If (_slaves IsNot Nothing) Then
  65.             For Each i As Viewport3D In _slaves
  66.                 Dim mv As ModelVisual3D = DirectCast(i.Children(0), ModelVisual3D)
  67.                 Dim t3dg As Transform3DGroup = DirectCast(mv.Transform, Transform3DGroup)
  68.                 Dim _GroupScaleTransform As ScaleTransform3D = DirectCast(t3dg.Children(0), ScaleTransform3D)
  69.                 Dim _GroupRotateTransform As RotateTransform3D = DirectCast(t3dg.Children(1), RotateTransform3D)
  70.                 Dim _GroupTranslateTransform As TranslateTransform3D = DirectCast(t3dg.Children(2), TranslateTransform3D)
  71.                 _GroupScaleTransform.ScaleX = s
  72.                 _GroupScaleTransform.ScaleY = s
  73.                 _GroupScaleTransform.ScaleZ = s
  74.                 _GroupRotateTransform.Rotation = New AxisAngleRotation3D(q.Axis, q.Angle)
  75.                 _GroupTranslateTransform.OffsetX = t.X
  76.                 _GroupTranslateTransform.OffsetY = t.Y
  77.                 _GroupTranslateTransform.OffsetZ = t.Z
  78.             Next i
  79.         End If
  80.     End Sub

  81.     Private Sub Reset()
  82.         _rotation = New Quaternion(0, 0, 0, 1)
  83.         _scale = 1
  84.         _translate.X = 0
  85.         _translate.Y = 0
  86.         _translate.Z = 0
  87.         _translateDelta.X = 0
  88.         _translateDelta.Y = 0
  89.         _translateDelta.Z = 0
  90.          _rotationDelta = Quaternion.Identity
  91.         _scaleDelta = 1
  92.         UpdateSlaves(_rotation, _scale, _translate)
  93.     End Sub

  94.     Private Sub MouseMoveHandler(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs)
  95.         If Not Enabled Then Return
  96.         e.Handled = True
  97.         Dim el As UIElement = DirectCast(sender, UIElement)
  98.         If el.IsMouseCaptured Then
  99.             Dim delta As Vector = _point - e.MouseDevice.GetPosition(el)
  100.             Dim t As Vector3D = New Vector3D
  101.             delta /= 2
  102.             Dim q As Quaternion = _rotation
  103.             If (_rotating = True) Then
  104.                   Dim mouse As Vector3D = New Vector3D(delta.X, -delta.Y, 0)
  105.                 Dim axis As Vector3D = Vector3D.CrossProduct(mouse, New Vector3D(0, 0, 1))
  106.                 Dim len As Double = axis.Length
  107.                 If (len < 0.00001 OrElse _scaling) Then
  108.                     _rotationDelta = New Quaternion(New Vector3D(0, 0, 1), 0)
  109.                 Else
  110.                     _rotationDelta = New Quaternion(axis, len)
  111.                 End If
  112.                 q = _rotationDelta * _rotation
  113.             Else
  114.                 delta /= 20
  115.                 _translateDelta.X = delta.X * -1
  116.                 _translateDelta.Y = delta.Y
  117.             End If
  118.             t = _translate + _translateDelta
  119.             UpdateSlaves(q, _scale * _scaleDelta, t)
  120.         End If
  121.     End Sub
  122.     Private Sub MouseDoubleClickHandler(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
  123.         Reset()
  124.     End Sub

  125.     Private Sub MouseUpHandler(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
  126.         If (Not _enabled) Then Return
  127.         e.Handled = True
  128.         If (_rotating = True) Then
  129.             _rotation = _rotationDelta * _rotation
  130.         Else
  131.             _translate += _translateDelta
  132.             _translateDelta.X = 0
  133.             _translateDelta.Y = 0
  134.         End If
  135.          Dim el As UIElement = DirectCast(sender, UIElement)
  136.         el.ReleaseMouseCapture()
  137.     End Sub

  138.     Sub OnMouseWheel(ByVal sender As Object, ByVal e As System.Windows.Input.MouseWheelEventArgs)
  139.         e.Handled = True
  140.         _scaleDelta += (e.Delta / 1000)
  141.         Dim q As Quaternion = _rotation
  142.         UpdateSlaves(q, _scale * _scaleDelta, _translate)
  143.     End Sub

  144.     Private Sub MouseDownHandler(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
  145.         If Not Enabled Then Return
  146.         e.Handled = True

  147.         If (Keyboard.IsKeyDown(Key.F1) = True) Then
  148.             Reset()
  149.             Return
  150.         End If
  151.         Dim el As UIElement = DirectCast(sender, UIElement)
  152.         _point = e.MouseDevice.GetPosition(el)
  153.         If (Not _centered) Then
  154.             Dim camera As ProjectionCamera = DirectCast(_slaves(0).Camera, ProjectionCamera)
  155.             _center = camera.LookDirection
  156.             _centered = True
  157.         End If
  158.         _scaling = (e.MiddleButton = MouseButtonState.Pressed)
  159.         If (Keyboard.IsKeyDown(Key.Space) = False) Then
  160.             _rotating = True
  161.         Else
  162.             _rotating = False
  163.         End If
  164.         el.CaptureMouse()
  165.     End Sub
  166. End Class


複製代碼
最後再加入 page的程式碼(web表單)


  1. Option Strict On
  2. Option Explicit On
  3. Imports System
  4. Imports System.Data
  5. Imports System.Windows
  6. Imports System.Windows.Data
  7. Imports System.Configuration
  8. Imports System.Windows.Media
  9. Imports System.Windows.Media.Media3D
  10. Imports System.Windows.Media.Animation
  11. Imports System.Windows.Media.Imaging
  12. Imports System.Reflection
  13. Imports System.Windows.Controls
  14. Imports System.Windows.Input
  15. Imports System.Windows.Threading
  16. Imports System.IO
  17. Public Class Page1

  18.     Dim _trackball As Trackball
  19.     Private Sub OnLoaded(ByVal sender As Object, ByVal e As EventArgs)
  20.         _trackball = New Trackball()
  21.         _trackball.Attach(Me)
  22.         _trackball.Slaves.Add(myViewport3D)
  23.         _trackball.Enabled = True
  24.     End Sub
  25.     Private Sub OnImage1Animate(ByVal sender As Object, ByVal e As RoutedEventArgs)
  26.         Dim s As Storyboard
  27.         s = DirectCast(Me.FindResource("RotateStoryboard"), Storyboard)
  28.         Me.BeginStoryboard(s)
  29.     End Sub

  30. End Class

複製代碼

作者: 路人甲    時間: 2008-3-28 08:42

 這個程式在我的電腦上幾乎是跑不動的,
不過在我公司的電腦跑起來真的是順的不得了(cpu使用率在5%以下)
很可能和顯卡有關  (nvidia geforce 8600gt),顯然 GPU 做了大部分的事來讓cpu空閒
看過相關資料,wpf會盡量利用硬體加速,在這裡得到證明了嗎,我不知道
作者: bauann    時間: 2008-3-31 11:13     標題: Gird

Grid這個"容器"相較之前的容器來看,顯的比較複雜一些,需要設定的東西比較多,下面用簡單的程式碼展示一下基本的功能,希望大家對於Grid能有一些基本的了解
  1. Dim gd As Grid
  2.     Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
  3.         gd = New Grid
  4.         Me.Title = "Grid Test"
  5.         ''設定Form的大小跟Content的長、寬是一樣的
  6.         Me.SizeToContent = Windows.SizeToContent.WidthAndHeight
  7.         Me.Content = gd
  8.         ''為了方面觀看變化,我們把隔線設定為顯示
  9.         gd.ShowGridLines = True
  10.         ''為了範例需要我們把新增欄、列的新增跟按鈕的新增分開處理
  11.         For iRow As Integer = 0 To 4
  12.             ''新增Grid的列
  13.             Dim rd = New RowDefinition
  14.             If iRow = 4 Then
  15.                 ''最後一列為了展示跨越欄位的button,這邊做特殊設定
  16.                 ''可以自行修改看看GridUnitType的部分看看有什麼不同
  17.                 rd.Height = New GridLength(100, GridUnitType.Star)
  18.             Else
  19.                 rd.Height = GridLength.Auto
  20.             End If
  21.             gd.RowDefinitions.Add(rd)
  22.         Next
  23.         For iCol As Integer = 0 To 4
  24.             ''新增Grid的欄
  25.             Dim cd As New ColumnDefinition
  26.             If iCol = 4 Then
  27.                 cd.Width = New GridLength(100, GridUnitType.Star)
  28.             Else
  29.                 cd.Width = GridLength.Auto
  30.             End If
  31.             gd.ColumnDefinitions.Add(cd)
  32.         Next
  33.         For z As Integer = 0 To 3
  34.             For x As Integer = 0 To 3
  35.                 Dim btn As New Button
  36.                 btn.Name = "Button" & z & "_" & x
  37.                 btn.Content = "Button " & z & "-" & x
  38.                 btn.Margin = New Thickness(2)
  39.                 Grid.SetColumn(btn, x)
  40.                 Grid.SetRow(btn, z)
  41.                 gd.Children.Add(btn)
  42.             Next
  43.         Next
  44.         Dim btnBig As New Button
  45.         btnBig.Name = "btnBig"
  46.         btnBig.Content = "Big Button"
  47.         btnBig.Margin = New Thickness(2)
  48.         Grid.SetRow(btnBig, 4)
  49.         Grid.SetColumn(btnBig, 0)
  50.         ''設定跨越Grid的三格,如果是跨越Row的話是用SetRowSpan
  51.         Grid.SetColumnSpan(btnBig, 3)
  52.         gd.Children.Add(btnBig)
  53.     End Sub
複製代碼





歡迎光臨 NCIS資訊中心討論區 (http://www.ncis.com.tw/ncis_bbs/) Powered by Discuz! 7.0.0