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

如何在.NET Maui中获取拖放项的绝对位置?

在.NET Maui中通过DropGestureRecognizer获取拖放项的绝对位置

核心实现思路

DropGestureRecognizer的Drop事件本身不直接返回拖放项的绝对屏幕位置,但可以通过.NET Maui内置的VisualElement.TranslateToPoint方法,将拖放项的相对坐标转换为屏幕绝对坐标。关键是要在拖放开始时把源元素的引用传递到Drop事件中。

代码示例

XAML布局

<StackLayout Padding="20">
    <!-- 拖放目标区域 -->
    <Frame BackgroundColor="LightGray" HeightRequest="300">
        <Label Text="拖放到这里" HorizontalOptions="Center" VerticalOptions="Center">
            <Label.GestureRecognizers>
                <DropGestureRecognizer Drop="OnDrop" AllowDrop="True" />
            </Label.GestureRecognizers>
        </Label>
    </Frame>

    <!-- 可拖放元素 -->
    <BoxView x:Name="DraggableBox" Color="Crimson" WidthRequest="60" HeightRequest="60" Margin="0,20,0,0">
        <BoxView.GestureRecognizers>
            <DragGestureRecognizer CanDrag="True" DragStarting="OnDragStarting" />
        </BoxView.GestureRecognizers>
    </BoxView>
</StackLayout>

后台逻辑

private void OnDragStarting(object sender, DragStartingEventArgs e)
{
    // 将源元素存入拖放数据中,供Drop事件使用
    if (sender is VisualElement sourceElement)
    {
        e.Data.Properties.Add("SourceElement", sourceElement);
    }
}

private void OnDrop(object sender, DropEventArgs e)
{
    // 取出拖放的源元素
    if (e.Data.Properties.TryGetValue("SourceElement", out var sourceObj) && sourceObj is VisualElement sourceElement)
    {
        // 以元素自身左上角为相对原点(坐标(0,0)),转换为屏幕绝对坐标
        Point absolutePosition = sourceElement.TranslateToPoint(new Point(0, 0));
        
        // 输出或使用绝对位置
        Console.WriteLine($"拖放项绝对位置:X = {absolutePosition.X:F2}, Y = {absolutePosition.Y:F2}");
    }
}

关键说明

  • TranslateToPoint方法会自动处理布局层级、滚动偏移(如在ScrollView内)等情况,返回的是元素相对于设备屏幕左上角的绝对坐标。
  • .NET Maui的拖放功能已完善支持该场景,不存在功能未实现的问题,只是需要手动通过坐标转换实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:12:54