Reputation: 13
I have this function that create an ObservableCollection<MenuBody>
to create my Xamarin.Forms user menu.
private ObservableCollection<MenuBody> _userList;
public ObservableCollection<MenuBody> UserList
{
set { SetProperty(ref _userList, value); }
get { return _userList; }
}
private void LoadUserMenu()
{
UserList = new ObservableCollection<MenuBody>
{
new MenuBody
{
Id = 1,
Text = "Principal",
Icon = IconFont.FileSignature,
},
new MenuBody
{
Id = 2,
Text = "Configurações",
Icon = IconFont.Cog,
},
};
}
XAML CollectionView bind properties:
<CollectionView
x:Name="MyUserCollectionView"
BackgroundColor="Transparent"
ItemsSource="{Binding UserList}"
SelectionMode="Single"
SelectionChangedCommand="{Binding MenuUserTappedCommand}"
SelectionChangedCommandParameter="{Binding SelectedItem,
Source{x:ReferenceMyUserCollectionView}}"
Function that I'm using to detect the user tap on menu.
private DelegateCommand<object> _menuUserTappedCommand;
public DelegateCommand<object> MenuUserTappedCommand =>
_menuUserTappedCommand ?? (_menuUserTappedCommand = new DelegateCommand<object>(ExecuteMenuUserTappedCommand));
async void ExecuteMenuUserTappedCommand(object parameter)
{
await App.Current.MainPage.DisplayAlert("Message", "Item " + parameter + " clicked", "Ok");
}
And I'm trying to access the MenuBody Id attribute from here:
I tried to write as parameter.Id
to reference it, but it doesn't appear as expected.
Can anyone help me find out where I'm wrong?
Upvotes: 0
Views: 193
Reputation: 89117
either cast it
var item = (MenuBody)parameter;
// then you can use item.Id
or use the correct type instead of object
public DelegateCommand<MenuBody> MenuUserTappedCommand =>
_menuUserTappedCommand ?? (_menuUserTappedCommand = new DelegateCommand<MenuBody>(ExecuteMenuUserTappedCommand));
async void ExecuteMenuUserTappedCommand(MenuBody parameter)
{
await App.Current.MainPage.DisplayAlert("Message", "Item " + parameter.Id + " clicked", "Ok");
}
Upvotes: 1