c# - 单击行时将动态值传递给事件处理程序
问题描述
请看下面的代码:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App1"
x:Class="App1.MainPage">
<ContentPage.BindingContext>
<local:PersonViewModel />
</ContentPage.BindingContext>
<StackLayout>
<ListView x:Name="listView" ItemsSource="{Binding People}">
<ListView.Header>
<Grid>
<Grid.BindingContext>
<local:PersonViewModel />
</Grid.BindingContext>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Grid.Column="1" Text="Id" />
<Label Grid.Column="2" Text="First Name" />
<Label Grid.Column="3" Text="Surname" />
<Label Grid.Column="4" Text="Date Of Birth" />
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Grid.Column="1" Text="{Binding Id}" />
<Label Grid.Column="2" Text="{Binding FirstName}" />
<Label Grid.Column="3" Text="{Binding Surname}" />
<Label Grid.Column="4" Text="{Binding Age}" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
和下面的视图模型:
public class PersonViewModel
{
private ObservableCollection<Person> _people = new ObservableCollection<Person>();
public ObservableCollection<Person> People
{
get { return _people; }
}
public PersonViewModel()
{
_people.Add(new Person { Id = Guid.NewGuid().ToString(), Age = 36, FirstName = "Andrew", Surname = "Smith" });
_people.Add(new Person { Id = Guid.NewGuid().ToString(), Age = 65, FirstName = "David", Surname = "White" });
_people.Add(new Person { Id = Guid.NewGuid().ToString(), Age = 39, FirstName = "Bert", Surname = "Edwards" });
}
}
它按预期工作,即网格被添加到页面中。如果用户点击其中一行;我希望将该行的 ID 传递给事件处理程序。我该怎么做呢。我花了过去三个小时研究这个,但我还没有找到答案。我发现的最接近的是:https ://forums.xamarin.com/discussion/23002/how-do-you-detect-a-grid-click-tap 。但是,在这种情况下,传递的是静态值而不是动态值。
解决方案
我假设您想要对象的 ID,而不是行(因为这不相关恕我直言)
所以,Listview 有一个 ItemTapped 事件:
<ListView x:Name="listView"
ItemTapped="TappedListView"
ItemsSource="{Binding People}">
而且,在您的 Page.xaml.cs
private void TappedListView(object sender, ItemTappedEventArgs e)
{
var yourItem = e.Item as Person;
var id = yourItem.Id;
}
您可以在官方文档中阅读更多关于 Listview Interactivity 的信息
推荐阅读
- javascript - 在javascript左右与左右分配值给const
- javascript - jquery左右滑动到div下一个或后退
- json - 将json文件读取为json字符串并在jsr223采样器中提取数据,groovy作为jmeter中的语言
- c# - http请求按钮。目的地无法到达
- javascript - 球体体积计算器
- sql - 访问 SQL 计算
- c - C中pi的无限级数逼近不终止
- java - 使用正则表达式和转义字符拆分 Java 字符串
- php - 根据 Woocommerce 中的产品类别按项目自定义电子邮件通知
- sql-server - 基于总和计算 Percetange