I have this in XAML:
<CollectionView ItemsSource="{Binding Accepted}"
SelectionMode="Single" SelectionChanged="OnAcceptedSelected">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding friendlyname}"/>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
And this is the OnClick handler:
async void OnAcceptedSelected(object sender, SelectionChangedEventArgs e) {
MyItem selectedMI = e.CurrentSelection.FirstOrDefault() as MyItem;
// do something
}
I want to be able to do different things with selectedMI depending on what column the user clicked on, something like this:
<CollectionView ItemsSource="{Binding Accepted}"
SelectionMode="Single" SelectionChanged="OnAcceptedSelected">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding friendlyname}"/>
<Label x:Name="Action_A" />
<Label x:Name="Action_B" />
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
so that I could do something like this:
async void OnAcceptedSelected(object sender, SelectionChangedEventArgs e) {
MyItem selectedMI = e.CurrentSelection.FirstOrDefault() as MyItem;
// if clicked on Action_A do something and
// if clicked on Action_B do something else
}
Xamarin doesn't seem to offer an obvious way to do that. Any ideas how to implement this functionality? Thanks.
CodePudding user response:
Adding gesture to Label is a good choice.
I wrote a small example for your reference.
Two labels are added to each row of the CollectionView, and two events are respectively bound. Clicking on a different label will enter two different methods, and you can get the information of the label you clicked inside the method.
Here is the xaml code:
<CollectionView ItemsSource="{Binding Accepted}" >
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding .}" BackgroundColor="Red" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="tapCommand"/>
</Label.GestureRecognizers>
</Label>
<Label Text="{Binding .}" BackgroundColor="blue" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="tapCommand1"/>
</Label.GestureRecognizers>
</Label>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Here is the background code:
public partial class MainPage : ContentPage
{
public ObservableCollection<string> Accepted { get; set; }
public MainPage()
{
Accepted = new ObservableCollection<string>();
Accepted.Add("aaa");
Accepted.Add("bbb");
Accepted.Add("ccc");//Simulation data
InitializeComponent();
BindingContext = this;
}
private void tapCommand(object sender, EventArgs e)//event1
{
string res = (sender as Label).Text;
}
private void tapCommand1(object sender, EventArgs e)//event2
{
string res = (sender as Label).Text;
}
}