【发布时间】:2021-05-04 21:36:27
【问题描述】:
我知道如何添加一个集合视图并用我的数据库中的数据填充它。我也知道如何在 collectionview 中选择一行并从不在我的 collectionview 中的按钮中删除该行(如页面底部的按钮) 但是我想做的是在每个单元格中创建一个删除/删除按钮,当单击相应的按钮时,我需要获取集合视图的选定索引并将其删除。
我需要的问题和帮助是如何为相应行中的每个按钮编写 buttonclick 事件。
请帮忙。
这是我的代码:
Customer.cs
命名空间测试
{
公开课客户
{
公共 int ID { 获取;放; }
公共字符串名称 { 获取;放; }
}
}
***MainPage.cs***
namespace TEST
{
public partial class MainPage : ContentPage
{
public ObservableCollection<Customers>CustomerCollection;
private int _itemId = 0;
public MainPage()
{
InitializeComponent();
CreateCustomerItems();
}
private void CreateCustomerItems()
{
CustomerCollection = new ObservableCollection<Customers>()
{
new Customers(){Id = 134, Name = "John Roberts"},
new Customers(){Id = 145, Name = "Olyvia Johnson"},
new Customers(){Id = 154, Name = "Paul Cippone"},
new Customers(){Id = 163, Name = "Robert Jones"},
new Customers(){Id = 171, Name = "Shannon Richards"},
new Customers(){Id = 186, Name = "Tamica Alvirez"},
new Customers(){Id = 195, Name = "Frank Bellford"},
new Customers(){Id = 204, Name = "Kathryn Brown"},
};
CvTest.ItemsSource = CustomerCollection;
}
public void Delete(Object Sender, EventArgs args)
{
//THIS IS WHERE I AM LOST I CAN GET THE DATA BELOW WITH COLLECTION VIEW SELECTION CHANGED BUT HOW CAN I ACHIEVE THAT HERE?
var btn = (Button)Sender;
//var item = (MainPage)btn.BindingContext;
//item.
CustomerCollection.Remove //THIS IS WHERE I AM LOST
}
private async void CvTest_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var currentSelection = e.CurrentSelection.FirstOrDefault() as Customers;
if (currentSelection == null) return;
_itemId = currentSelection.Id;
await DisplayAlert("Testing", "You selected the CollectionView with the customer id of: " + _itemId.ToString(), "Continue");
}
}
}
***MainPage.xaml***
<CollectionView x:Name="CvTest" SelectionMode="Single" SelectionChanged="CvTest_SelectionChanged">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Text="{Binding Id}" Grid.Column="0" Grid.Row="0" HorizontalOptions="Center"/>
<Label Text="{Binding Name}" Grid.Column="0" Grid.Row="1" HorizontalOptions="Center"/>
<Button Text="Delete" Grid.Column="0" Grid.Row="2" Clicked="Delete"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
【问题讨论】:
标签: xamarin xamarin.forms