gpt4 book ai didi

listview - Xamarin Forms 如何制作可拖动的 ListView

转载 作者:行者123 更新时间:2023-12-02 19:25:38 25 4
gpt4 key购买 nike

是否可以使用 Xamarin 表单创建具有可拖动列表项的 ListView ?

我在下面的链接中找到了在 android 中实现的这一点的引用,但我不确定如何在 Xamarin.Forms 中实现这一点,我假设我需要为此添加特定于平台的代码?

How to make a ListView with draggable items?

此外,正如下面的 Xamarin 论坛帖子所示,控件似乎不支持拖放功能,因此需要创建自定义渲染器,但我不太确定从哪里开始

http://forums.xamarin.com/discussion/18114/do-the-xamarin-forms-controls-support-drag-drop-runtime-functionality

最佳答案

对于 iOS,您可以利用 native UITableView控件的重新排序功能。为 ListView 创建自定义渲染器这告诉 iOS 您希望所有行都可移动。让它更新源列表的顺序以匹配用户的操作。

从子类开始。

public class EditListView : ListView { }

然后添加一个更新 ListView.ItemsSource 的自定义渲染器以反射(reflect)更改后的顺序。此代码假设 ItemsSourceList<ListItem> ,其中ListItemIdName字符串类型的属性。

[assembly: ExportRenderer(typeof(EditListView), typeof(EditListViewRenderer))]
public class EditListViewRenderer : ListViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
{
base.OnElementChanged(e);

if (e.NewElement != null) {
Control.Source = new TableViewSource((List<ListItem>)e.NewElement.ItemsSource);
Control.Editing = true;
}
}

class TableViewSource : UITableViewSource
{
readonly List<ListItem> items;

public TableViewSource(List<ListItem> items) { this.items = items; }

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var item = items[indexPath.Row];
var cell = new UITableViewCell(UITableViewCellStyle.Default, item.Id); // No recycling. If the list is big enough to need recycling, the user won't be very happy about reordering it by hand. :-)
cell.TextLabel.Text = item.Name;
return cell;
}

public override void MoveRow(UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath)
{
int source = sourceIndexPath.Row, dest = destinationIndexPath.Row;
var movedItem = items[source];
items.RemoveAt(source);
if (source > dest) --source;
items.Insert(dest, movedItem);
}

public override nint RowsInSection(UITableView tableview, nint section) => items.Count;
public override bool CanMoveRow(UITableView tableView, NSIndexPath indexPath) => true;
public override bool CanEditRow(UITableView tableView, NSIndexPath indexPath) => true; // Only editable rows can be moved.
public override bool ShouldIndentWhileEditing(UITableView tableView, NSIndexPath indexPath) => false;
public override UITableViewCellEditingStyle EditingStyleForRow(UITableView tableView, NSIndexPath indexPath) => UITableViewCellEditingStyle.None;
}
}

关于listview - Xamarin Forms 如何制作可拖动的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25147107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com