#741 – 使用触摸事件移动控件(Using Touch Manipulation Events to Translate an Element)

来源:互联网 发布:淘宝卖家互刷平台 编辑:程序博客网 时间:2024/06/06 23:16

原文地址:https://wpf.2000things.com/2013/01/24/741-using-touch-manipulation-events-to-translate-an-element/

你可以通过使用触摸操作事件在屏幕上移动控件。让控件随着手指的移动在屏幕上移动。

首先,需要设置需要接收触摸操作事件的控件的IsManipulationEnabled 属性为true ,来开启控件接收触摸操作事件。同时还要为ManipulationStarting 和ManipulationDelta 事件注册事件处理函数。

<Canvas Name="canvMain" Background="Transparent">    <Image Source="JamesII.jpg" Width="100"           IsManipulationEnabled="True"           RenderTransform="{Binding ImageTransform}"           ManipulationStarting="Image_ManipulationStarting" ManipulationDelta="Image_ManipulationDelta"/></Canvas>

上面的代码中,允许用户通过手指移动图像。我们绑定图片控件的RenderTransform 属性为一个MatrixTransform 类型的实例(后面在代码中定义)。该实例包含一个控制图像“缩放”、“旋转”和“位移”的矩阵。在我们这个例子中,我们只在ManipulationDelta事件中修改矩阵控制位移部分的矢量。

public partial class MainWindow : Window, INotifyPropertyChanged{    public MainWindow()    {        InitializeComponent();        this.DataContext = this;         ImageTransform = new MatrixTransform(); // XAML中绑定的MatrixTransform 实例    }     private MatrixTransform imageTransform;    public MatrixTransform ImageTransform    {        get { return imageTransform; }        set        {            if (value != imageTransform)            {                imageTransform = value;                RaisePropertyChanged("ImageTransform");            }        }    }     private void Image_ManipulationStarting(object sender, ManipulationStartingEventArgs e)    {        // Ask for manipulations to be reported relative to the canvas        e.ManipulationContainer = canvMain;    }     private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)    {        ManipulationDelta md = e.DeltaManipulation;  // 获取当前操作的最新更改        Vector trans = md.Translation;  //获取操作在屏幕上水平和垂直移动信息        // Update matrix to reflect translation        Matrix m = imageTransform.Matrix;        m.Translate(trans.X, trans.Y);  // 设置图像在屏幕上的水平和垂直移动距离        imageTransform.Matrix = m;        RaisePropertyChanged("ImageTransform");         e.Handled = true;    }     public event PropertyChangedEventHandler PropertyChanged;     private void RaisePropertyChanged(string prop)    {        if (PropertyChanged != null)            PropertyChanged(this, new PropertyChangedEventArgs(prop));    }}


阅读全文
0 0
原创粉丝点击