|
| 1 | +@implements IDisposable |
| 2 | + |
| 3 | +<div style="padding:20px"> |
| 4 | + <TelerikBreadcrumb Data="@Items" Width="100%"></TelerikBreadcrumb> |
| 5 | +</div> |
| 6 | + |
| 7 | +@code { |
| 8 | + |
| 9 | + [Inject] private NavigationManager NavigationManager { get; set; } |
| 10 | + |
| 11 | + public List<BreadcrumbItem> Items { get; set; } |
| 12 | + |
| 13 | + //Create a handler that will be invoked on each location change |
| 14 | + private void OnLocationChanged(object sender, LocationChangedEventArgs e) |
| 15 | + { |
| 16 | + var relativeLocation = NavigationManager.ToBaseRelativePath(e.Location); |
| 17 | + SetBreadcrumbs(relativeLocation); |
| 18 | + } |
| 19 | + |
| 20 | + //Bind the above handler to the NavigationManager's LocationChanged event |
| 21 | + protected override void OnInitialized() |
| 22 | + { |
| 23 | + NavigationManager.LocationChanged += OnLocationChanged; |
| 24 | + var relativeLocation = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); |
| 25 | + |
| 26 | + //Set new breadcrumb items on each invocation |
| 27 | + SetBreadcrumbs(relativeLocation); |
| 28 | + |
| 29 | + base.OnInitialized(); |
| 30 | + } |
| 31 | + |
| 32 | + //Sets new breadcrumbs based on the current URL. Called on initial page load as well as on every subsequent location change |
| 33 | + public void SetBreadcrumbs(string relativeLocation) |
| 34 | + { |
| 35 | + var newItems = new List<BreadcrumbItem>() { new BreadcrumbItem { Icon = "home", Url = NavigationManager.BaseUri } }; |
| 36 | + |
| 37 | + var locationCrumbs = relativeLocation.Split('/'); |
| 38 | + string url = NavigationManager.BaseUri; |
| 39 | + |
| 40 | + foreach (var crumb in locationCrumbs) |
| 41 | + { |
| 42 | + if (!string.IsNullOrEmpty(crumb)) |
| 43 | + { |
| 44 | + url += crumb; |
| 45 | + newItems.Add(new BreadcrumbItem { Text = crumb, Url = url, Title = crumb }); |
| 46 | + url += "/"; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + Items = newItems; |
| 51 | + StateHasChanged(); |
| 52 | + } |
| 53 | + |
| 54 | + void IDisposable.Dispose() |
| 55 | + { |
| 56 | + // Unsubscribe from the event when disposed |
| 57 | + NavigationManager.LocationChanged -= OnLocationChanged; |
| 58 | + } |
| 59 | + |
| 60 | + public class BreadcrumbItem |
| 61 | + { |
| 62 | + public string Text { get; set; } |
| 63 | + public string Url { get; set; } |
| 64 | + public string Title { get; set; } |
| 65 | + public string Icon { get; set; } |
| 66 | + } |
| 67 | +} |
0 commit comments