I am trying to get the clicked item on my collection view (what a noble idea).
I am happy with the inner workings of my view:
<CollectionView SelectionChangedCommand="{Binding ClickCommand}" SelectionMode="Single" SelectionChangedCommandParameter="{Binding SelectedItem}" VerticalOptions="FillAndExpand" ItemsSource="{Binding WifiHotSpots}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10">
<Label Text="{Binding .}" FontAttributes="Bold" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
I am also happy with having the click being registered inside my command:
[RelayCommand]
public void Click(object obj)
{
}
... however, I am unhappy with my obj
not containing anything. It is null.
How can I return the clicked item?
EDIT: The selected Item (which was just a test I believe):
private object _selectedItem;
public object SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItem));
}
}
}
I am answering this:
I am trying to get the clicked item on my collection view
First, specifying your Model class in your DataTemplate is mandatory:
<DataTemplate x:DataType="model:MyModel">
(Julian pointed out, that it is not mandatory, if you never specified your ViewModel, never skipped it myself, because I do not get binding typo warnings, TODO: test)
Second, I advise you to use tap gesture, let's say I have Grid in the DataTemplate:
<Grid.GestureRecognizers>
<TapGestureRecognizer...
Third, the way you go get to the ViewModel, and execute the command is with:
<TapGestureRecognizer CommandParameter="{Binding .}"
Command="{Binding Source={RelativeSource AncestorType=
{x:Type viewmodel:MyViewModel}}, Path=MyCommand}"/>
It is the most basic way to get the clicked item.
When you see "model:MyModel" and "local:MainPage", "viewmodel:MyViewModel", you have to understand that MyModel, MainPage, MyViewModel are classes. And model, local, viewmodel are name spaces.
And let's say we have MainViewModel, that is at the top-level namespace of my application.
To use it for binding, you do this:
xmlns:local="clr-namespace:MyApp"
And after that you set your view model as DataType:
x:DataType="local:MyViewModel"
The same way you can add your model namespace as XML namespace and use it when setting DataType of the collection. And also the same way, you can specify your view model as type for the command binding. By declaring "viewmodel" name space.
You can pick any words, not just "model", "viewmodel" etc. It is just an example.