我想要一个按钮集合,将 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
接口并将它们放入IndexableObservableCollection
添加它们时,这将自动设置它们的索引。在 xaml 中你可以使用{Binding Index}
绑定到这个自动设置的索引。
希望这可以帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)