武汉北大青鸟中南软件学院
400-027-0822

WPF如何获取UI元素的图像

2016-03-25供稿中心: 北大青鸟武汉中南软件学院

比如我想在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>

   点击中间的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);


关于我们
首页
公司简介
课程专业
师资力量
高薪就业
青鸟课程
ACCP
学士后Java
基础教育
UI设计
回到首页