Skip to content

Commit 5164f1d

Browse files
Drawer selected item sync (#112)
* feat(drawer): show how to sync selected item with external navigation * docs: explain drawer item sync
1 parent 4dae468 commit 5164f1d

33 files changed

+1359
-0
lines changed

drawer/select-on-load/readme.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Sync Selected Drawer Item on Load and Navigation
2+
3+
If you use the built-in drawer items for navigation, the selected (highlighted) one will update automatically.
4+
5+
If you navigate through other means such as directly land on a page from and external link, or use internal Blazor navigation (such as `<NavLink>` or `<a>` elements), the selected (highlighted) item in the drawer will become out of sync with the currently active page.
6+
7+
This happens because the drawer cannot know that the navigation happened in order to update itself. Moreover, even if it were to handle such events from the `NavigationManager`, updating the selected item means raising the `SelectedItemChanged` event, which can cause non-deterministic behavior. Generally, the event is a result of a user action (like clicking on a drawer item) and lets the app react to that. If it starts firing without a user action, it can cause infinite loops and the execution of business logic when it is not intended.
8+
9+
Thus, the solution to ensure external navigation keeps the correct item selected is to select it with application code when the desired events occur.
10+
11+
This sample project shows the two most common scenarios:
12+
13+
* Internal navigation from elements outside the drawer. This is handled through the `LocationChanged` event of the `NavigationManager`.
14+
15+
* Selecting an item on load, regardless of which page the user lands on. This is done through the `OnInitialized` lifecycle method.
16+
17+
Both examples are in the `~/Shared/MainLayout.razor` file, and code commends provide more information. They both rely on a couple of helper methods that are also in the same file.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 16
4+
VisualStudioVersion = 16.0.31515.178
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "select-on-load", "select-on-load\select-on-load.csproj", "{8854F53F-702A-4ACE-A628-A16E8382B352}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{8854F53F-702A-4ACE-A628-A16E8382B352}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{8854F53F-702A-4ACE-A628-A16E8382B352}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{8854F53F-702A-4ACE-A628-A16E8382B352}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{8854F53F-702A-4ACE-A628-A16E8382B352}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {E8356352-F6A6-4B83-A923-8840B144EA65}
24+
EndGlobalSection
25+
EndGlobal
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
2+
<Found Context="routeData">
3+
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
4+
</Found>
5+
<NotFound>
6+
<LayoutView Layout="@typeof(MainLayout)">
7+
<p>Sorry, there's nothing at this address.</p>
8+
</LayoutView>
9+
</NotFound>
10+
</Router>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using System;
2+
3+
namespace select_on_load.Data
4+
{
5+
public class WeatherForecast
6+
{
7+
public DateTime Date { get; set; }
8+
9+
public int TemperatureC { get; set; }
10+
11+
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12+
13+
public string Summary { get; set; }
14+
}
15+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using System;
2+
using System.Linq;
3+
using System.Threading.Tasks;
4+
5+
namespace select_on_load.Data
6+
{
7+
public class WeatherForecastService
8+
{
9+
private static readonly string[] Summaries = new[]
10+
{
11+
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
12+
};
13+
14+
public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
15+
{
16+
var rng = new Random();
17+
return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
18+
{
19+
Date = startDate.AddDays(index),
20+
TemperatureC = rng.Next(-20, 55),
21+
Summary = Summaries[rng.Next(Summaries.Length)]
22+
}).ToArray());
23+
}
24+
}
25+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
@page "/counter"
2+
3+
<h1>Counter</h1>
4+
5+
<p>Current count: @currentCount</p>
6+
7+
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
8+
9+
@code {
10+
private int currentCount = 0;
11+
12+
private void IncrementCount()
13+
{
14+
currentCount++;
15+
}
16+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
@page "/fetchdata"
2+
3+
@using select_on_load.Data
4+
@inject WeatherForecastService ForecastService
5+
6+
<h1>Weather forecast</h1>
7+
8+
<p>This component demonstrates fetching data from a service.</p>
9+
10+
@if (forecasts == null)
11+
{
12+
<p><em>Loading...</em></p>
13+
}
14+
else
15+
{
16+
<table class="table">
17+
<thead>
18+
<tr>
19+
<th>Date</th>
20+
<th>Temp. (C)</th>
21+
<th>Temp. (F)</th>
22+
<th>Summary</th>
23+
</tr>
24+
</thead>
25+
<tbody>
26+
@foreach (var forecast in forecasts)
27+
{
28+
<tr>
29+
<td>@forecast.Date.ToShortDateString()</td>
30+
<td>@forecast.TemperatureC</td>
31+
<td>@forecast.TemperatureF</td>
32+
<td>@forecast.Summary</td>
33+
</tr>
34+
}
35+
</tbody>
36+
</table>
37+
}
38+
39+
@code {
40+
private WeatherForecast[] forecasts;
41+
42+
protected override async Task OnInitializedAsync()
43+
{
44+
forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
45+
}
46+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
@page "/"
2+
3+
<h1>Hello, world!</h1>
4+
5+
Welcome to your new app.
6+
7+
<SurveyPrompt Title="How is Blazor working for you?" />
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
@page "/"
2+
@namespace select_on_load.Pages
3+
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
4+
@{
5+
Layout = null;
6+
}
7+
8+
<!DOCTYPE html>
9+
<html lang="en">
10+
<head>
11+
<meta charset="utf-8" />
12+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
13+
<title>select-on-load</title>
14+
<base href="~/" />
15+
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
16+
<link href="css/site.css" rel="stylesheet" />
17+
<link href="select-on-load.styles.css" rel="stylesheet" />
18+
<link rel="stylesheet" href="_content/Telerik.UI.for.Blazor/css/kendo-theme-default/all.css" />
19+
<script src="_content/Telerik.UI.for.Blazor/js/telerik-blazor.js" defer></script>
20+
</head>
21+
<body>
22+
<component type="typeof(App)" render-mode="ServerPrerendered" />
23+
24+
<div id="blazor-error-ui">
25+
<environment include="Staging,Production">
26+
An error has occurred. This application may no longer respond until reloaded.
27+
</environment>
28+
<environment include="Development">
29+
An unhandled exception has occurred. See browser dev tools for details.
30+
</environment>
31+
<a href="" class="reload">Reload</a>
32+
<a class="dismiss">🗙</a>
33+
</div>
34+
35+
<script src="_framework/blazor.server.js"></script>
36+
</body>
37+
</html>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using Microsoft.AspNetCore.Hosting;
2+
using Microsoft.Extensions.Configuration;
3+
using Microsoft.Extensions.Hosting;
4+
using Microsoft.Extensions.Logging;
5+
using System;
6+
using System.Collections.Generic;
7+
using System.Linq;
8+
using System.Threading.Tasks;
9+
10+
namespace select_on_load
11+
{
12+
public class Program
13+
{
14+
public static void Main(string[] args)
15+
{
16+
CreateHostBuilder(args).Build().Run();
17+
}
18+
19+
public static IHostBuilder CreateHostBuilder(string[] args) =>
20+
Host.CreateDefaultBuilder(args)
21+
.ConfigureWebHostDefaults(webBuilder =>
22+
{
23+
webBuilder.UseStartup<Startup>();
24+
});
25+
}
26+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"iisSettings": {
3+
"windowsAuthentication": false,
4+
"anonymousAuthentication": true,
5+
"iisExpress": {
6+
"applicationUrl": "http://localhost:29865",
7+
"sslPort": 44344
8+
}
9+
},
10+
"profiles": {
11+
"IIS Express": {
12+
"commandName": "IISExpress",
13+
"launchBrowser": true,
14+
"environmentVariables": {
15+
"ASPNETCORE_ENVIRONMENT": "Development"
16+
}
17+
},
18+
"select-on-load": {
19+
"commandName": "Project",
20+
"dotnetRunMessages": "true",
21+
"launchBrowser": true,
22+
"applicationUrl": "https://localhost:5001;http://localhost:5000",
23+
"environmentVariables": {
24+
"ASPNETCORE_ENVIRONMENT": "Development"
25+
}
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)