You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WPF中Rectangle的ManipulationDelta事件仅触发一次如何解决

问题根因

你遇到的事件仅在边界触发的问题由两个核心错误导致:

  • 未对触摸设备做捕获处理,触摸按下后系统没有持续将触摸事件路由到Rectangle控件
  • TouchMove事件中错误使用Mouse.GetPosition获取坐标,没有读取触摸事件自带的触摸点信息

解决步骤

1. 调整XAML代码

补充TouchDown、TouchUp事件绑定,原有配置可保留:

<Window x:Class="WpfApp5.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp5"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid Margin="0,0,-322,-112">
    <Rectangle 
        ManipulationDelta="Rectangle_ManipulationDelta"
        TouchMove="Rectangle_TouchMove"
        TouchDown="Rectangle_TouchDown"
        TouchUp="Rectangle_TouchUp"
        Fill="#FFF4F4F5" 
        HorizontalAlignment="Left" 
        Height="274" Margin="162,70,0,0" 
        Stroke="Black" 
        VerticalAlignment="Top" 
        Width="582" IsManipulationEnabled="True"/>
    
    <TextBlock 
        x:Name="textBlock" 
        HorizontalAlignment="Left" 
        TextWrapping="Wrap" 
        VerticalAlignment="Top" 
        Margin="31,26,0,0"><Run Text="TextBlock"/></TextBlock>
</Grid>
</Window>

2. 修改后台C#逻辑

namespace WpfApp5{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Rectangle_TouchDown(object sender, TouchEventArgs e)
        {
            var rect = sender as Rectangle;
            rect?.CaptureTouch(e.TouchDevice);
            e.Handled = true;
        }

        private void Rectangle_TouchMove(object sender, TouchEventArgs e)
        {
            // 如需获取相对于整个窗口的坐标,将sender替换为Application.Current.MainWindow即可
            var touchPoint = e.GetTouchPoint(sender as IInputElement).Position;
            textBlock.Text = $"触摸坐标:X={touchPoint.X:F2}, Y={touchPoint.Y:F2}";
            e.Handled = true;
        }

        private void Rectangle_TouchUp(object sender, TouchEventArgs e)
        {
            var rect = sender as Rectangle;
            rect?.ReleaseTouchCapture(e.TouchDevice);
            e.Handled = true;
        }

        private void Rectangle_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            // 若需要处理多指平移、缩放等手势,可在此处通过e.DeltaManipulation获取手势参数
        }
    }
}

补充说明

调整完成后触摸滑动时会持续触发TouchMove事件,实时输出坐标,不会出现仅边界触发的问题。如果需要同时支持手势操作,保留ManipulationDelta的相关逻辑即可,和触摸捕获逻辑不冲突。

内容的提问来源于stack exchange,提问作者nfszero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:57:03