我想要一组按钮,将它们在 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/