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