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

标签 xaml xamarin.forms

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

相关文章:

c# - 如何保护我的 Windows Phone 8.1 应用程序?

visual-studio-2015 - 无法在 xamarin.Forms 可移植项目中使用 WebClient

android - 如何将 View (例如标签)的高度/宽度设置为其内容的大小?

c# - Master和Detail must be set before adding MasterDetailPage to a container 错误在Xamarin forms中

xamarin.forms - Xamarin 形式的流畅设计

c# - 如何使用单独的 WpfControlLibrary 中的 ResourceDictionary 将样式设置为 Prism 6 模块中的 RadioButton?

c# - 在 TreeView 中显示 "root"节点

wpf - 正确单击数据网格中的按钮时,Telerik RadGridView 选定项绑定(bind)不起作用

c# - 将 wpf 窗口聚焦在快捷键上

azure - 设备未以 xamarin 形式在 azure 推送通知中心注册