WPF实例秀——如何获取UI元素的图像
WPF实例秀——如何获取UI元素的图像
这个标题还真难说明白,我还是再解释一下吧。
比如我想在UI上拖拽某个元素,拖拽过程中,我需要让这个UI元素的影相跟着鼠标移动(但UI还停留在原位),当放开鼠标的时候,UI元素移动到新的位置。
这是个很常见的需求,实现这个需求的第一步就是获取这个UI元素的影相。实现这一步其实很简单,核心就是使用VisualBrush这个画刷子类。
下面我给出一个简单的例子。
这是UI描述,
- <Windowx: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">
- <GridMargin="10">
- <Grid.ColumnDefinitions>
- <ColumnDefinitionWidth="160"/>
- <ColumnDefinitionWidth="*"/>
- <ColumnDefinitionWidth="160"/>
- </Grid.ColumnDefinitions>
- <StackPanelx:Name="stackPanelLeft"Background="White">
- <Buttonx:Name="btn"Content="OK"Height="40"/>
- </StackPanel>
- <ButtonContent=">>>"Grid.Column="1"Margin="5"Click="Button_Click"/>
- <StackPanelx:Name="stackPanelRight"Background="White"Grid.Column="2"/>
- </Grid>
- </Window>
UI效果是这样的
点击中间的Button,会把左边StackPanel中Button的影像加入到右边的StackPanel中。代码如下(核心是使用VisualBrush):
- privatevoidButton_Click(objectsender,RoutedEventArgse)
- {
- VisualBrushvbrush=newVisualBrush(btn);
- Rectanglerect=newRectangle();
- rect.Width=btn.Width;
- rect.Height=btn.Height;
- rect.Fill=vbrush;
- rect.Opacity=0.5;//为了表示是影像,我让不透明度为50%
- this.stackPanelRight.Children.Add(rect);
- }
点击几下后,结果如下图:
核心问题解决了,剩下的就好办了。如果想做出拖拽等效果,只是些使用Mouse事件和计算偏移量的小技俩了:p
====================================
我写了一个完整的例子,上传到资源里了,可惜不知道为什么显示不出来。名字叫“WPF拖拽效果源代码”。等我自己能看见了,就把链接贴过来~~~
放个截图先~~~~