gpt4 book ai didi

xaml - 如何在 BindableLayout.ItemsSource 中绑定(bind)项目的索引

转载 作者:行者123 更新时间:2023-12-04 15:46:02 26 4
gpt4 key购买 nike

我想要一组按钮,将它们在 MyObservableCollection 中的相应项目的索引显示为文本,并使用 CommandParameter 也作为此索引执行命令。我怎样才能做到这一点?

<StackLayout BindableLayout.ItemsSource="{Binding MyObservableCollection}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Button Text="{Binding [index of the item in MyObservableCollection]}"
Command="{Binding MyCommand}"
CommandParameter="{Binding [index of the item in MyObservableCollection]}" />
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>

最佳答案

所以让我们以正确的“非黑客”方式做你在评论中提到的“黑客”事情^^

我会按照以下方式构建一些东西。首先我们制作一个 IIndexable界面:

public interface IIndexable
{
int Index { get; set; }
}

我们现在自己实现 ObservableCollection<T>像这样:
public class IndexableObservableCollection<T> : ObservableCollection<T> where T : IIndexable
{
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Move:
for (int i = 0; i < e.NewItems.Count; i++)
if (e.NewItems[i] is IIndexable indexableItem)
indexableItem.Index = e.NewStartingIndex + i;
break;
}
base.OnCollectionChanged(e);
}
}

现在我只在这里完成了 switch 中最基本的实现(在这种情况下,switch 可以用 if 语句替换,但这使你更容易实现所有选项),你必须看看进 NotifyCollectionChangedEventArgs自己并相应地实现案例。

在此之后,您希望能够显示实现 IIndexable 的索引的类。接口(interface)并将它们放入 IndexableObservableCollection这将在添加它们时自动设置它们的索引。在 xaml 中,您可以使用 {Binding Index}绑定(bind)到这个自动设置的索引。

希望这可以帮助

关于xaml - 如何在 BindableLayout.ItemsSource 中绑定(bind)项目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55742763/

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