![](/img/trans.png)
[英]How to get access viewcell by index from ListView object in xamarin forms?
[英]How to get ListView item index from custom ViewCell in Xamarin Forms?
我創建了一個具有自定義 ViewCell 的 ListView,如下所示:
<ListView x:Name="ListView1" ItemTapped="ListView1_ItemTapped"
SeparatorVisibility="None" RowHeight="192" HasUnevenRows="False"
FlowDirection="RightToLeft" CachingStrategy="RecycleElement" >
<ListView.ItemTemplate>
<DataTemplate>
<custom:ViewCell1 />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
這是自定義 ViewCell 的 XAML
<ViewCell.View>
<StackLayout>
<Label Text="{Binding Name}" />
<Label Text="{Binding ID}" />
<Button x:Name="Button1" Text="Get index" Clicked="Button1_Clicked" />
</StackLayout>
</ViewCell.View>
我所需要的只是當我單擊 Button1 時,我得到 ListView1 項目索引(或 ViewCell 索引)
問題是我無法從自定義 ViewCell 后面的代碼中的 Button1_Clicked 事件訪問 ListView1 並獲取 ListView1 的點擊項目索引(甚至獲取 ViewCell 的點擊項目索引)。
我搜索了很多,發現可以通過3種方式完成:
1- 為 ViewCell 創建一個附加屬性以獲取其索引。
2- 使用 ViewCell 的索引器並獲取它的索引。
3-使用此問題中提到的 ITemplatedItemsView 界面
但不幸的是,我無法從后面的自定義 ViewCell 代碼中的 Button1_Clicked 事件中實現它們中的任何一個,因為我不是 MVVM 或 C# 方面的專家。
請給我一個專家幫助。
謝謝
有很多方法可以實現它。 如果您不熟悉數據綁定和 MVVM。 我將提供最簡單的方法。
首先,在 ItemSource 的 model 中添加一個屬性。
public class YourModel
{
public int Index { get; }
//other properties like name and ID
public YourModel(int index)
{
Index = index;
}
}
並在初始化ListView的ItemSource時設置Index的值。
sources = new ObservableCollection<YourModel>() { };
for(int i=0;i<20;i++)
{
sources.Add(new YourModel(i) { /**other propertes**/});
}
在自定義單元格中
得到它像下面
var model = this.BindingContext as YourModel;
int index = model.Index;
嘗試使用Button1.Parent.Parent.Parent...
等等,除非你得到你的listview
的 object。
還要在按鈕的CommandParameter
中傳遞viewcell
的BindingContext
,例如CommandParameter={Binding}
,然后從ItemsSource
獲取收到的 object 的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.