主界面的代碼
<StackPanel ButtonBase.Click="Grid_Click"> <Button Content="逐漸變大縮小"/> <Button Content="鼠標移動特效" /> </StackPanel>
cs :
//這事件不做過多的解釋有基礎的一看就會明白 private void Grid_Click(object sender, RoutedEventArgs e) { object obj = e.OriginalSource; Button butn = null; if (obj is Button) butn = obj as Button; Type type = this.GetType();//獲取當前實例 Assembly assembly = type.Assembly;//獲取在其中聲明的類型 //動態的實例化一個對象 Window win = (Window)assembly.CreateInstance(type.Namespace + "." + butn.Content.ToString()); win.Show(); } 下面進行第一個動畫: xaml界面 <Grid> <Button Content="點擊逐漸增長" Height="45" HorizontalAlignment="Left" Margin="29,37,0,0" Name="btnGrow1" VerticalAlignment="Top" Width="213" /> <Button Content="點擊逐漸歸位" Height="23" HorizontalAlignment="Left" Margin="86,88,0,0" Name="btnBack" VerticalAlignment="Top" Width="90" /> <Button Content="點擊增長" Height="46" HorizontalAlignment="Left" Margin="98,161,0,0" Name="btnGrow" VerticalAlignment="Top" Width="78" /> </Grid> cs: public 逐漸變大縮小() { InitializeComponent(); //給button注冊點擊事件 btnGrow1.Click += new RoutedEventHandler(btnGrow1_Click); btnBack.Click += new RoutedEventHandler(btnBack_Click); btnGrow.Click += new RoutedEventHandler(btnGrow_Click); } //點擊增長 void btnGrow_Click(object sender, RoutedEventArgs e) { DoubleAnimation widthAnimation = new DoubleAnimation() { By=50,Duration=TimeSpan.FromSeconds(0.2) }; btnGrow.BeginAnimation(Button.WidthProperty, widthAnimation); } //還原動畫 void btnBack_Click(object sender, RoutedEventArgs e) { DoubleAnimation widthAmination = new DoubleAnimation(); widthAmination.Duration = TimeSpan.FromSeconds(1); DoubleAnimation heightAmimation = new DoubleAnimation(); heightAmimation.Duration = TimeSpan.FromSeconds(1); btnGrow1.BeginAnimation(Button.WidthProperty, widthAmination); btnGrow1.BeginAnimation(Button.HeightProperty, heightAmimation); } //逐漸增長事件 void btnGrow1_Click(object sender, RoutedEventArgs e) { DoubleAnimation widthAnimation = new DoubleAnimation() { To = this.Width - 30, Duration = TimeSpan.FromSeconds(1) }; DoubleAnimation heightAnimation = new DoubleAnimation() { To=(this.Height-40)/3, Duration=TimeSpan.FromSeconds(1) }; btnGrow1.BeginAnimation(Button.WidthProperty, widthAnimation); btnGrow1.BeginAnimation(Button.HeightProperty, heightAnimation); }
好了現在的一個簡單點擊放大縮小的動畫就做好了
小結:1,本例中在菜單窗體中用到了用到了一個 ButtonBase.Click特別說明一下這個事件很好用如果一個界面上的按鈕很多
每個事件都需要彈出一個窗體用這個最好用,節省代碼,
2,在WPF中要實現動畫就需要DoubleAnimation這個類,按照自己的想法從初始狀態From定義到結束To狀態在多長事件內完成Duration
最后需要一個控件來觸發動畫例如:
btnGrow1.BeginAnimation(Button.WidthProperty, widthAnimation);
這段代碼的意思就是
btnGrow1控件點擊是觸發widthAnimation這個動畫,影響的對象就是這個控件的width
好了就寫到這里,以后還會有,wpf,很有意思,相比起winform來他的界面更加靈活,代碼編寫也更加靈活,
界面的色彩也很好定義,另外動畫也可以下載axml中,但是本人不喜歡在界面設計窗台上寫這些,在后台寫的話跟能看的清楚。