如何在 Xamarin.Forms 的列表视图中获取所选项目的坐标? [英] How to get coordinates of the selected item in a list view in Xamarin.Forms?
问题描述
我想获取列表视图中所选项目相对于屏幕的坐标(矩形边界:x、y、宽度和高度)(假设列表视图填满整个屏幕),以便我可以在该位置并为其设置动画以在我的 Xamarin.Forms 应用中显示所选项目的一些详细信息.
I want to get the coordinates (rectangle bounds: x, y, width and height) of the selected item in the listview relative to the screen (assume the listview fills the whole screen), so that I can create an object at that location and animate it to display some details of the selected item in my Xamarin.Forms app.
xaml 中的列表视图:
listview in xaml:
<ListView ItemTapped="ItemTapped"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="0.5, 0.5, 1.0, 1.0">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Height="50">
<AbsoluteLayout>
<Label Text="{Binding Info}"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="0.1, 0.5, 0.7, 0.5"/>
</AbsoluteLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ItemTapped 事件的 c# 代码:
c# code for ItemTapped event:
void ItemTapped(object sender, EventArgs args)
{
var listView = (ListView)sender; // the listview
var selectedItem = args.Item; // the selected item
// need to get selected item coordinates for the animation
var selectedItemBounds = ...
...
}
最终我想在 Xamarin.Forms 中使用列表视图创建类似这样的内容(列表视图中的对象数量各不相同):
Eventually I want to create somehting like this in Xamarin.Forms with a listview (the number of objects in the listview varies):
推荐答案
一个简单的想法:
有一个作为单例运行的视图助手服务:
Have a view helper service which runs as a singleton:
interface IViewHelper
{
Rect GetScreenCoordinates(View view);
}
在 ListView 项模板和点击事件处理程序调用中的 AbsoluteLayout 上添加点击手势:
Have a tap gesture added on the AbsoluteLayout you have in the ListView item template, and in the tap event handler call:
IViewHelper viewHelper = CrossViewHelper.Instance;
Rect rcItem = viewHelper.GetScreenCoordinates((View)sender);
服务 GetScreenCoordinates
的本机实现做了两件事:
The native implementation of the service GetScreenCoordinates
does two things:
// Get the native view from the Xamarin Forms view
var nativeView = Platform.GetRenderer(view);
// Call native functions to get screen coordinates
Android: nativeView.GetLocationOnScreen(coords)
iOS: Use nativeView.ConvertPoint(coords, null)
见https://forums.xamarin.com/discussion/86941/get-xy-co-ordinates-in-tap-gesture-inside-listview
另见:https://michaelridland.com/xamarin/creating-native-view-xamarin-forms-viewpage/
我没有完整的代码,但我希望这可以帮助您.
I don't have a complete code, but I hope this can help you.
我认为最后,在您实现动画并显示视图之后,您可以将实现重构为一个很好的行为,您可以附加到任何视图,它是否在列表视图中并不重要,它会只是工作.
I think in the end, after you implement animating and showing the view, you can refactor the implementation into a nice Behavior you can attach to any view, it won't matter if it's inside list-view or not, it will just work.
这篇关于如何在 Xamarin.Forms 的列表视图中获取所选项目的坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!