First of all, when you use the ItemClick event , the "sender" is not your Menu class; it is a GridView control itself. So your code is var link = (sender as Menu).Link; should get a null reference exception.
Here I can offer two ways to do this work, but all these two methods use the SelectionChanged event as follows:
private void gridView_SelectionChanged(object sender, SelectionChangedEventArgs e) { var link = (gridView.SelectedItem as Menu).Link; Frame.Navigate(link); }
First, define two properties in your Menu class as follows:
public class Menu { public Type Link { get; set; } public string Name { get; set; } }
And use the GridView as follows:
<GridView x:Name="gridView" ItemsSource="{x:Bind menu}" SelectionChanged="gridView_SelectionChanged"> <GridView.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" FontSize="25" /> </DataTemplate> </GridView.ItemTemplate> </GridView>
code for adding data to the GridView :
private ObservableCollection<Menu> menu = new ObservableCollection<Menu>(); public MainPage() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { menu.Clear(); menu.Add(new Menu { Link = typeof(Link1), Name = typeof(Link1).Name }); menu.Add(new Menu { Link = typeof(Link2), Name = typeof(Link2).Name }); menu.Add(new Menu { Link = typeof(Link3), Name = typeof(Link3).Name }); }
Secondly, you can simply define one property in the Menu class, but use a converter to display the name of each page.
Menu class:
public class Menu { public Type Link { get; set; } }
Converter TypeToStringConverter :
public class TypeToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { if (value == null) return "Error"; var link = (value as Menu).Link; return link.Name; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } }
And you can use this converter and GridView in XAML as follows:
<Page.Resources> <local:TypeToStringConverter x:Key="cvt" /> </Page.Resources> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <GridView x:Name="gridView" ItemsSource="{x:Bind menu}" SelectionChanged="gridView_SelectionChanged"> <GridView.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Converter={StaticResource cvt} }" FontSize="25" /> </DataTemplate> </GridView.ItemTemplate> </GridView> </Grid>
code for adding data to the GridView :
private ObservableCollection<Menu> menu = new ObservableCollection<Menu>(); public MainPage() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { menu.Clear(); menu.Add(new Menu { Link = typeof(Link1) }); menu.Add(new Menu { Link = typeof(Link2) }); menu.Add(new Menu { Link = typeof(Link3) }); }