WPF實例秀——如何獲取UI元素的圖像

WPF實例秀——如何獲取UI元素的圖像
 
這個標題還真難說明白,我仍是再解釋一下吧。
 
好比我想在UI上拖拽某個元素,拖拽過程當中,我須要讓這個UI元素的影相跟着鼠標移動(但UI還停留在原位),當放開鼠標的時候,UI元素移動到新的位置。
 
這是個很常見的需求,實現這個需求的第一步就是獲取這個UI元素的影相。實現這一步其實很簡單,核心就是使用VisualBrush這個畫刷子類。
 
下面我給出一個簡單的例子。
 
這是UI描述,
  1. <Window x:Class="WpfApplicationImage.Window1"
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     Title="Window1" Height="300" Width="400" Background="SteelBlue">
  5.     <Grid Margin="10">
  6.         <Grid.ColumnDefinitions>
  7.             <ColumnDefinition Width="160"/>
  8.             <ColumnDefinition Width="*"/>
  9.             <ColumnDefinition Width="160"/>
  10.         </Grid.ColumnDefinitions>
  11.         <StackPanel x:Name="stackPanelLeft" Background="White">
  12.             <Button x:Name="btn" Content="OK" Height="40"/>
  13.         </StackPanel>
  14.         <Button Content=">>>" Grid.Column="1" Margin="5" Click="Button_Click"/>
  15.         <StackPanel x:Name="stackPanelRight" Background="White" Grid.Column="2"/>
  16.     </Grid>
  17. </Window>
UI效果是這樣的
 
點擊中間的Button,會把左邊StackPanel中Button的影像加入到右邊的StackPanel中。代碼以下(核心是使用VisualBrush):
 
  1.         private void Button_Click(object sender, RoutedEventArgs e)
  2.         {
  3.             VisualBrush vbrush = new VisualBrush(btn);
  4.             Rectangle rect = new Rectangle();
  5.             rect.Width = btn.Width;
  6.             rect.Height = btn.Height;
  7.             rect.Fill = vbrush;
  8.             rect.Opacity = 0.5; //爲了表示是影像,我讓不透明度爲50%
  9.             this.stackPanelRight.Children.Add(rect);
  10.         }
點擊幾下後,結果以下圖:
 
核心問題解決了,剩下的就好辦了。若是想作出拖拽等效果,只是些使用Mouse事件和計算偏移量的小技倆了:p
====================================
我寫了一個完整的例子,上傳到資源裏了,惋惜不知道爲何顯示不出來。名字叫「WPF拖拽效果源代碼」。等我本身能看見了,就把連接貼過來~~~
 
放個截圖先~~~~
相關文章
相關標籤/搜索