Dynamically registering pages
Eduardo Gomez
3,431
Reputation points
I am using Shell, and registering pages is a pain. So, I created a way to dynamically registering them, but for some reason it doesn't work as expected. Appsell.cs
private void RegisterPages() {
// Get the assembly where this code is executing
var assembly = GetType().Assembly;
// Define the namespace where the views are located using a constant or variable
var viewNamespace = $"{assembly.GetName()}.{Helpers.Constants.VIEWS}";
// Dictionary to hold discovered routes, mapping route names to their respective types
var pageRoutes = new Dictionary<string, Type>();
// Loop through types in the assembly to find view pages and map them to their routes
foreach(var item in assembly.GetTypes()) {
// Check if the type belongs to the specified view namespace and ends with a defined "Page" suffix
if(item.Namespace == viewNamespace && item.Name.EndsWith(Helpers.Constants.PAGE)) {
// Get the route name from the type's name
var routeName = item.Name;
// Add the route name and its associated type to the dictionary
pageRoutes.Add(routeName, item);
}
}
// Register each discovered route in the application's routing system
foreach(var kvp in pageRoutes) {
// Register the route using its name and associated type
Routing.RegisterRoute(kvp.Key, kvp.Value);
}
}
for example: I have an app, that download things off the internet, and it will go to a detail Page. if I try to navigate ViewModel
async Task SelectedItemAsync(Movie movie) {
if(movie is not null) {
await Shell.Current.GoToAsync($"{nameof(DetailPage)}", true,
new Dictionary<string, object> {
{"Movie", Movies}
});
}
{"Relative routing to shell elements is currently not supported. Try prefixing your uri with ///: ///DetailPage"} However, if I do this Appshell.cs
Routing.RegisterRoute(nameof(DetailPage), typeof(DetailPage));
it works fine, why? And how to make it dinamically demo https://github.com/eduardoagr/MauiVideo
Sign in to answer