美好的一天, 我正在使用集合视图来查看 Xamarin Forms 中的用户地址列表,并且数据模板中有一个图像,供用户点击以编辑任何所需的地址。请参阅下面的代码。我的问题是,当用户点击图像并将其显示在另一个页面中进行编辑和保存时,如何获取地址详细信息。
<CollectionView x:Name="addressCollectionList"
SelectionMode="Single"
SelectionChanged="addressCollectionList_SelectionChanged"
Margin="15">
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical"/>
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="5">
<Frame BorderColor="#009688" CornerRadius="20">
<StackLayout Spacing="10" VerticalOptions="Center" Orientation="Horizontal">
<Label Text="{Binding addressName}"/>
<Image Source="ic_edit.png" HorizontalOptions="EndAndExpand">
<Image.GestureRecognizers>
<TapGestureRecognizer x:Name="editAddress" Tapped="editAddress_Tapped"/>
</Image.GestureRecognizers>
</Image>
</StackLayout>
</Frame>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
根据您是否使用MVVM,有两种方法。
对于MVVM
<TapGestureRecognizer Command="{Binding YourCommand}" CommandParameter={Binding .}/>
并收到它就像
YourCommand= new Command<Type>((selectedItem)=>{
});
对于非 MVVM:
<TapGestureRecognizer Tapped="EditAddress_Tapped" CommandParameter={Binding .}/>
像这样得到它:
private void EditAddress_Tapped(object sender, EventArgs e)
{
var tappedEvgs = e as TappedEventArgs;
var data = tappedEvgs.Parameter;
}
您可以通过代码后面的 findbyname 来访问它。这将让您访问与您按下的图像相关的标签。
在 xaml 中为标签命名:
<Label x:Name="MyLabel" Text="{Binding addressName}"/>
然后在后面的代码中:
private async void editAddress_Tapped(object sender, EventArgs e)
{
var SenderButton = (Image)sender;
var _label = SenderButton.Parent.FindByName<Label>("MyLabel");
}