Démonstration de personnalisation du thème de la visionneuse de rapports de bout en bout

Ceci est le troisième et dernier article d'une série détaillant comment styliser une application sur toutes les plates-formes, en écrivant une fois et en livrant partout. Cet article concerne l'application de notre thème personnalisé aux visionneuses de rapports dans nos applications Web et de bureau.
Series Outline
Ceci est le troisième et dernier article d'une série détaillant
comment styliser l'application sur toutes les plates-formes, écrire une fois et livrer
partout. Cet article concerne l'application de notre thème personnalisé aux téléspectateurs de rapports dans
nos applications Web et de bureau.
- Élégant
et interface utilisateur personnalisable pour tout système de conception et technologie - Telerik
et personnalisation du thème de l'interface utilisateur Kendo : démonstration Web et de bureau - Telerik Reporting Modern UI : démonstration de la visionneuse de rapports (ce message)
Introduction
Jusqu'à ce point de la série, nous avons conceptuellement
examiné l'importance des thèmes élégants et personnalisables, créé un thème personnalisé,
et utilisé ce thème dans diverses applications Web et de bureau. Cependant, je parie
qu'une demande n'est jamais complète sans une fonction de rapport. C'est
où Rapport Telerik
est pratique.
Les rapports dans Telerik Reporting peuvent être conçus et stylisés dans
un nombre infini de façons. Nous laisserons comment faire cela pour un plus dédié
article. Dans ce cas, nous voulons comprendre comment ajouter un rapport personnalisé
composant qui permet de visualiser des rapports dans chacune de nos applications. Pour faire ça,
nous devrons comprendre les visionneuses de rapports. Passons ensuite en revue les visionneuses de rapports.
Présentation des visionneuses de rapports
Rapport
Les visualiseurs sont des composants d'interface utilisateur qui sont utilisés pour afficher des rapports dans les applications.
Nous proposons une pléthore de visionneuses de rapports pour le Web et le bureau. Le rapport web
les visionneuses sont construites sur la visionneuse de base HTML5.
Le rapport de bureau
les visionneuses sont intégrées nativement dans l'application de bureau.
De plus, nos applications Report Viewer dans la démo
nécessitera l'utilisation du Reporting
Service REST . C'est parce que les visualiseurs de rapports sont des clients pour afficher le
rapports et le Reporting REST Service est un service de traitement et
rendre le rapport. Les visualiseurs de rapports ne peuvent pas afficher un rapport sans REST
Service. Cela signifie que nous devrons également ajouter le service Reporting REST à notre
Application Blazor pour travailler avec nos applications clientes. En conséquence, nous allons
faites un léger détour et ajoutez ceci à notre solution ensuite.
Création du service REST de reporting
Pour commencer, je vais juste copier ma fin
résultat du Post
02 Référentiel de code source dans un dossier Post 03. Ensuite, nous commencerons par un
projet de base ASP.NET Core WebApi (fig. 01).
Figure 01 : Créer un ASP.NET vide Coeur
Projet WebApi
Ensuite, il y a trois étapes générales pour créer le
Service de rapports REST dans ASP.NET Core 5.0. Ce sont des packages Ajouter NuGet,
Mettez à jour la classe Startup.cs et implémentez le ReportsController. Pour plus de détails
étapes, voir Comment
pour héberger le service de rapports dans ASP.NET Core dans .NET 5. Passons en revue le
étapes générales ci-dessous.
Ajouter des packages NuGet
Nous ajouterons le Telerik.ReportingTelerik.Reporting.OpenXmlRendering,
Telerik.Reporting.WebServiceDataSourceNewtonsoft.Json et le DocumentFormat.OpenXmL
Paquets NuGet (fig. 02).
Il est important de noter que tous les packages ci-dessus ne sont pas
requis pour le service REST de génération de rapports, mais l'inclusion de tous fournira le plus
capacités. Par exemple, WebServiceDataSource n'est requis que si les rapports
utilisera un WebServiceDataSource et les packages OpenXML ne sont requis que si le rendu
rapports au format OpenXML de Microsoft (DOCX, PPTX, XLSX).
Figure 02 : Ajouter des packages NuGet
Mettre à jour le démarrage. cs Class
Nous utilisons des clients séparés par des domaines, nous aurons donc besoin
pour utiliser CORS dans ce scénario. De plus, nous apporterons les modifications nécessaires à
ajoutez la sérialisation Newtonsoft JSON et configurez le service Reporting REST dans
la méthode ConfigureService (code 01).
01.
public
void
ConfigureServices(IServiceCollection services)
02.
{
03.
// Ajouter Cors
04.
services.AddCors(opts =>
05.
{
06 .
opts.AddDefaultPolicy(p =>
07.
{
[1945010] 08.
p.AllowAnyMethod();
09.
p.90
10.
p.AllowAnyOrigin();
11.
[;
12.
});
13.
14.
// Ajout de la sérialisation Newtonsoft JSON
15.
services.AddControllers().AddNewtonsoftJson();
16.
17.
// Configurer les dépendances pour ReportsController.
18.
services.TryAddSingleton
19.
new
ReportServiceConfiguration
20.
{
21.
ReportingEngineConfiguration,[19spGetService()]
22.
HostAppId =
"Net5RestServiceWithCors"
,
[196593010
Storage =
new
FileStorage(),
24.
49 nouveau [196519659029]UriReportSourceResolver(
25.
System.IO.Path.Combine(sp.GetService
26.
});
27.
}
Extrait de code 01 : Startup.cs ConfigureServices
Méthode
Dans la méthode de configuration, nous devons utiliser CORS et nous assurer que les MapControllers sont ajoutés aux EndPoints (code 02).
01.
public[19659028]void
Configure (application IApplicationBuilder, environnement IWebHostEnvironment)
02.
{
03.
if
(env.IsDevelopment())
04.
{
05.
app.UseDeveloperExceptionPage();
06.
}
07.
08.
// Ajouter UseCors
09.
app.UseCors();
10.
11.
app.UseRouting();
12.
13.
app.UseAuthorization();
14.
15.
app.UseEndpoints(endpoints =>
16.
{
17 .
// Ajouter des MapControllers
18.
endpoints.MapControllers();
19659010]19.
});
20.
}
Extrait de code 02 : méthode de configuration Startup.cs
Implémenter le ReportsController
Dans le projet WebApi, nous pouvons utiliser Visual Studio
Scaffolding pour ajouter le contrôleur API. Sélectionnez le contrôleur API vide et le nom
it ReportsController (fig. 03).
Figure 03 : Ajouter un ReportsController vide
Après le ReportsController a été échafaudé, hérite
le ReportsControllerBase et implémenter le constructeur de base (code 03).
1.
[Route(
"api/[controller]"
)]
2.
[ApiController]
3.
public
class
ReportsController : ReportsControllerBase
[19659010]4.
{
5.
public
ReportsController(IReportServiceConfiguration reportServiceConfiguration)
6.
:
base
(reportServiceConfiguration)
7.
{ }
8.
}
Code Snippet 03 : ReportsController.cs
Enfin, nous pouvons exécuter le projet API. Un bon moyen de tester si
notre service REST fonctionne en naviguant vers api/reports/formats.
Cela produira un tableau JSON des données disponibles
formats de rapport (code 04).
01.
[
02.
{
"nom"
:
"PDF"
,
"nom localisé"
:
"Acrobat (PDF) fichier"
},
03.
{
"nom"
:
"CSV"
,
"nom localisé"
:
"CSV (délimité par des virgules)"
},
04.
{
"nom"
:
"XLSX"
,
"nom localisé"
:
"Excel Worksheet"
},
05.
{
"nom"
:
"PPTX"
,
"nom localisé"
:
"Présentation PowerPoint"
},
06.
{
"nom"
:
"RTF"
,
"nom localisé"
:
"Rich Text Format"
},
07.
{
"nom"
:
"IMAGE"
,
"nom localisé"
:
"Fichier TIFF"
},
08.
{
"nom"
:
"DOCX"
,
"nom localisé"
:
"Document Word"
}
09.
]
Extrait de code 04 : Formats de rapport disponibles
Avec le service de rapport REST maintenant mis en œuvre, nous pouvons
livrer nos rapports à distance à nos clients. Dans le reste de l'article, je vais
suivre le même ordre de Post 02. Nous allons continuer avec le Rapport angulaire
Visionneusele Rapport Blazor
Viewer et terminez avec le rapport WPF
Visionneuse. L'objectif global de cet article est d'examiner comment notre client personnalisé
le thème fonctionne dans les visionneuses de rapports Telerik Reporting, parcourez l'ajout d'un
Report Viewer à chaque application cliente et utilisez-la pour afficher des rapports.
Thème personnalisé pour les visualiseurs de rapports Web
Le véritable avantage ici est le style personnalisé qui a
été ajouté à nos applications clientes Web fonctionnera sans aucune étape supplémentaire.
Cela illustre la puissance du style et du thème personnalisés dans Telerik et Kendo UI.
Nous pouvons simplement ajouter les visualiseurs de rapports et profiter des avantages de nos précédents
efforts.
En fin de compte, cela fonctionne parce que le rapport en ligne
Les visionneuses sont toutes construites autour du même HTML5/JavaScript/CSS sous-jacent
qui utilise également les styles d'interface utilisateur Kendo prêts à l'emploi. Passons en revue
créer ensuite la visionneuse de rapport angulaire.
Créer la visionneuse de rapport angulaire
La création de la visionneuse de rapport dans une application angulaire est
aussi simple que d'ajouter les ressources requises, préparer les importations du module d'application
et les déclarations, et la création d'un composant de visualisation de rapports. Pour tous les détails
de cela, reportez-vous à notre Comment
À Angular Report Viewer avec l'article Angular CLI.
Ajouter jQuery et Telerik Angular Report Viewer
Pour ce faire, nous pouvons utiliser npm install jQuery @progress/telerik-angular-report-viewer
à partir de la ligne de commande. De plus, nous devrons mettre à jour
--save
la déclaration Angular build scripts pour inclure la distribution jQuery (fig.
04).
Figure 04: Ajouter jQuery à Angular Build
Créer le composant de rapports
Ici, nous pouvons utiliser l'échafaudage angulaire pour ajouter notre nouveau
composant également. Nous pouvons exécuter ng générer des rapports de composants
à partir du dossier src/app/components
.
Ajouter des importations et des déclarations à AppModule
Pour ajouter la visionneuse de rapport angulaire à notre projet, nous
besoin d'importer le TelerikReportingModule et de déclarer le nouveau
ReportsComponent dans l'AppModule. Cela devrait également inclure une nouvelle route comme
nous allons devoir naviguer jusqu'au composant (code 05). Notez les lignes 20, 21,
27, 38 et 50 dans l'extrait de code suivant.
01.
import { BrowserModule } de
'@angular/platform-browser'
;
02.
import { NgModule } depuis
'@angular/core'
;
03.
import { RouterModule, Routes } depuis [19659089]'@angular/router'
;
04.
import { BrowserAnimationsModule } de
'@angular/platform-browser/animations'
;
05.
import { ReactiveFormsModule, FormsModule } de
'@angular/forms'
;
06 .
import { AppComponent } depuis
'./app.component'
;
07.
import { MenuModule } depuis
'@ progress/kendo-angular-menu'
;
08.
import { GridModul e } de
'@progress/kendo-angular-grid'
;
09.
import { ChartsModule } de
'@progress/kendo -angular-charts'
;
10.
import { DropDownsModule } de
'@progress/kendo-angular-dropdowns'
;
11.
import { PopupModule } de
'@progress/kendo-angular-popup'
;
12 .
import { InputsModule } de
'@progress/kendo-angular-inputs'
;
13.
14.
import
'hammerjs'
;
15.
16.
import { HeaderComponent } de
'./components/header/header.component'
;
17.
import { HomeComponent } de
'./components/home/home.component'
;
18.
import { FooterComponent } de
'./components/ footer/footer.component'
;
19.
import { GridComponent } de
"./components/grid/grid.component"
;
20.
import { ReportsComponent } de
'./components/reports/reports.component'
;
21.
import { TelerikReportingModule } de
'@progress/telerik-angular-report-viewer'
;
22.
23.
routes const : Routes = [
24.
{ chemin :
''
redirectTo :
'home'
pathMatch :
'full'
},
[19659010]25.
{ chemin :
'home'
composant : HomeComponent },
26.
{ chemin :
'grid'
composant : GridComponent },
27.
{ chemin :
'reports'
composant : ReportsComponent},
28.
{ chemin :
'**'
redirectTo :
'home'
}
29.
] ;
30.
31.
@NgModule({
32.
déclarations : [
33.
AppComponent,
34 .
HeaderComponent,
35.
HomeComponent,
[19451904][19690]36] .
Composant de grille,
37.
Composant de pied de page,
[19453904][196904310] .
Composant de rapports
39.
],
40.
importe : [
41.
BrowserModule,
42.
ReactiveFormsModule,
43.
FormsModule
44.
MenuModule,
45.
[
Navigateur,Animateur
46.
GridModule,
47.
Charts
48.
RouterModule.forRoot(routes),
49.
[19659446]DropDownsModule, PopupModule, InputsModule,
[19659010]50.
TelerikReportingModule
51.
],
[19659010]52.
bootstrap : [AppComponent]
53.
})
54.
export class AppModule { }
Code Snippet 05 : Angular Grid app.module.ts
Créer le composant Angular Report Viewer
Enfin, nous pouvons créer notre Visionneuse de rapport angulaire. Nous
devons nous assurer que nous référençons notre nouveau service REST de rapport dans le serviceUrl
propriété du composant (code 06 & code 07).
Angular Report Viewer Markup
01.
<
kendo-dropdownlist
[data]="reportFiles" (selectionChange )="selectionChange($event)" [(ngModel)]="selectedReport"></
kendo-dropdownlist
>
02.
<
br
/>
03.
<
br
/>
04.
<
tr-viewer
#viewer1
05.
[containerStyle]="viewerContainerStyle"
07.
[viewMode]="'INTERACTIF'"
08.
[scaleMode]="'SPECIFIQUE'"
09.
[scale]="1.0"
10.
[ready]="prêt"
11.
[viewerToolTipOpening]="viewerToolTipOpening"
12.
[enableAccessibility]="false">
13.
</
tr-viewer
>
Extrait de code 06 : AngularGrid reports.component.html
Angular Report Viewer Component Code
01.
import { Component, AfterViewInit, ViewChild} de
'@angular/core'
;
02.
import { reportFiles } de
'src/app/common/files'
;
03.
import { TelerikReportViewerComponent } de
'@progress/telerik-angular-report-viewer'
;
04.
[19659010]05.
@Component({
06.
sélecteur :
'app-reports'
,
07.
templateUrl :
'./reports.component.html'
08.
})
09.
export class ReportsComponent implémente AfterViewInit {
10.
@ViewChild(
'viewer1'
{ statique :
false
}) visionneuse : TelerikReportViewerComponent ;
11.[19659033]
12.
public selectedReport =
"Dashboard.trdp"
;
13.
public reportFiles : chaîne[] = reportFiles;
14.
15.
title =
"Report Viewer"
;
16.
17.
viewerContainerStyle = {
18.
position :
'absolue'
,
19.
gauche :
'5px'
,
20.
à droite :
'5px'
,
21.
haut :
'200px'
,
22.
en bas :
'5px'
,
23.
débordement :
'caché'
,
24.
effacer :
'les deux'
,
25.
[
'font-family'
] :
'ms sans serif'
26.
} ;
27.
28.
constructeur() {
29.
30.
}
31.
32.
ngAfterViewInit() {
33.
var
rs = {
34.
rapport :
ce
.selectedReport
35.
} ;
36.
37.
this
.viewer.setReportSource(rs);
38.
}
39.
40.
public selectionChange(value : any):void {
41.
var
rs = {
42.
rapport : valeur
43.
} ;
44.
45.
ceci
.viewer.setReportSource(rs);
46.
}
47.
}
Code Snippet 07 : Angular Grid reports.component.ts
En tant que bonus, j'ai utilisé une liste déroulante pour sélectionner et modifier le
Source du rapport du composant Angular Report Viewer. J'ai également ajouté un itinéraire vers
le projet Reporting REST Service qui produira une liste JSON des
fichiers disponibles. Cependant, au lieu de créer un service dans le projet angulaire,
Je viens de coder cela en dur dans src/app/common/files.ts
export.
La sortie de la visionneuse de rapport angulaire suit notre
le thème et les éléments matériels peuvent également être vus à partir du composant déroulant comme
bien (fig. 05) .
Figure 05: Angular Report Viewer Animation
Ceci conclut la création de la visionneuse de rapport angulaire. Nous
avons examiné comment notre thème personnalisé existant est appliqué dans l'Angular
Report Viewer et a parcouru la mise en œuvre. Ensuite, nous passerons en revue les
Visionneuse de rapports Blazor.
Création du rapport Blazor
Visionneuse
Dans le R3
2021 Telerik Reporting Release nous avons ajouté la visionneuse de rapport Blazor
Modèle d'élément Visual Studio qui créera la visionneuse de rapports pour nous.
Cependant, pour ce projet, nous devons le faire manuellement pour illustrer le processus.
Créer la visionneuse de rapport Blazor revient à créer la visionneuse de rapport angulaire.
Ajoutez les dépendances, créez le composant, créez le Report Viewer et prenez
profit de nos efforts antérieurs. Puisque nous utilisons le Reporting REST
Service, nous avons seulement besoin de mettre à jour le client Wasm. Commençons.
Ajoutez la référence Telerik.ReportViewer.Blazor
Nous commencerons par ajouter la Telerik.ReportViewer.Blazor
Le package NuGet qui est disponible via le Telerik NuGet Feed (fig.
06). Pour
référence, cela peut être configuré dans Visual Studio ou via la ligne de commande
comme indiqué dans le Telerik Private
Documentation NuGet Feed.
Figure 06 : Ajouter le
Telerik.ReportViewer.Blazor Package
Ajouter des dépendances à Index.html
Il y a trois dépendances qui doivent être chargées dans le
fichier index.html. Ce sont interop.js, jQuery et Telerik Report Viewer
scripts (code 08). Notez les lignes 17, 18 et 31 dans l'extrait de code ci-dessous.
01.
02.
<
html
>
03.
<
tête
>
04.
<
meta
charset
=
"utf-8"
/>
05.
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0, maximum-scale= 1.0, user-scalable=no"
/>
06.
<
title
>BlankClientAspNetHostedBlazorApp</
title
>
07.
<
base
href
=
"/"
/>
09.
<
style
>
10.
corps {
11.
font-family : Roboto, sans-serif ;
12.
}
13.
</
style
>
14.
<
link
href
=
"css/site.css"
rel
=
"stylesheet"
/>
15.
<
link
href
=
"css/main.css"
rel
=
"stylesheet"
/>
16.
18.
<
script
src
=
"/api/reports/resources/js/telerikReportViewer"
></
script
>
19.
<
script
src
=
"_content/Telerik.UI.for.Blazor/js/telerik-blazor.js"
defer></
script
>
20.
</
head
>
21.
<
body
>
22.
<
div
id
=
"app"
>Loading...</
div
>
23.
24.
<
div
id
=
"blazor-error-ui"
>
25.
An unhandled error has occurred.
26.
<
a
href
=
""
class
=
"reload"
>Reload</
a
>
27.
<
a
class
=
"dismiss"
>🗙</
a
>
28.
</
div
>
29.
30.
<
script
src
=
"_framework/blazor.webassembly.js"
></
script
>
31.
<
script
src
=
"_content/Telerik.ReportViewer.Blazor/interop.js"
defer></
script
>
32.
</
body
>
33.
</
html
>
Code Snippet 08: Blazor Wasm Grid index.html
Create a Reports Razor Page
Next, we can add a new Reports Razor Component through
visual studio (fig. 07).
Figure 07: Add New Razor Component in
Visual Studio
Create the Blazor Report Viewer Component
Finally, we can add the Blazor Report Viewer usings,
styles, markup and code blocks.
Blazor Report Viewer Markup
Because we’re using the Reporting REST Service, we need
to inject the HttpClient (code 09). This is a common pattern with Wasm.
01.
@page "/reports"
02.
@using Telerik.ReportViewer.Blazor
03.
@inject HttpClient HttpClient;
04.
05.
<
h2
>Reports</
h2
>
06.
07.
<
style
>
08.
#rv1 {
09.
position: relative;
10.
width: 1000px;
11.
height: 800px;
12.
}
13.
</
style
>
14.
15.
<
TelerikDropDownList
Data
=
"@ReportList"
Value
=
"@SelectedReport"
OnChange
=
"ReportSelection"
></
TelerikDropDownList
>
16.
<
br
/>
17.
<
br
/>
18.
<!--
19.
The Report Viewer ServiceURL is set to the localhost and port of the TBACS.BlazorGridCustomStyle.Server project
20.
This may change for each development environment.
21.
See the launchSettings.json in that project for reference.
22.
-->
23.
<
ReportViewer
@
ref
=
"rv1"
ViewerId
=
"rv1"
24.
ServiceUrl
=
"/api/reports"
25.
Parameters
=
"@(new ParametersOptions { Editors = new EditorsOptions { MultiSelect = EditorType.ComboBox, SingleSelect = EditorType.ComboBox } })"
26.
ScaleMode
=
"@(ScaleMode.Specific)"
27.
Scale
=
"1.0"
/>
Code Snippet 09: Blazor Wasm Grid Markup
Blazor Report Viewer Code Block
We have also implemented selecting the Report Source
from a dropdown as well (code 10).
01.
public
string
SelectedReport {
get
;
set
; }
02.
public
List<
string
> ReportList {
get
;
set
; }
03.
public
ReportViewer rv1;
04.
public
ReportSourceOptions RSO {
get
;
set
; }
05.
06.
protected
async
override
Task OnInitializedAsync()
07.
{
08.
ReportList = await HttpClient.GetFromJsonAsync<List<
string
>>(
"/api/files"
);
09.
10.
SelectedReport =
"Dashboard.trdp"
;
11.
12.
RSO =
new
ReportSourceOptions
13.
{
14.
Report = SelectedReport
15.
};
16.
17.
await rv1.SetReportSourceAsync(RSO);
18.
await rv1.RefreshReportAsync();
19.
}
20.
21.
private
async Task ReportSelection(
object
report)
22.
{
23.
SelectedReport = report.ToString();
24.
25.
RSO =
new
ReportSourceOptions
26.
{
27.
Report = SelectedReport
28.
};
29.
30.
await rv1.SetReportSourceAsync(RSO);
31.
}
Code Snippet 10: Blazor Wasm Grid Code Block
Below is the output of the Blazor Report Viewer and how it
works with our custom styling (fig. 08).
Figure 08: Blazor Report Viewer Animation
This wraps up adding the Blazor Report Viewer to our
sample project. In this section, we walked through setting up the Blazor Report
Viewer and we didn’t have to make any changes to our styling. Everything worked
right out of the box as expected.
Overall, theming across our web frameworks and web report
viewers is quite easy. This is by design because they use the same styles and
resources. We were able to walk through setting up the report viewers in
Angular and Blazor. However, these same concepts can be applied to ASP.NET MVC,
ASP.NET AJAX, a plain HTML5/CSS/JS application, React or Vue. In the next
section, we will do the same for our desktop application.
Custom Theming for Desktop Report Viewers
Like when we created our custom themes for our WPF desktop application, adding the WPF Report Viewer is more involved. However, we still get to reap the benefits of our custom styles within the Report Viewer like the Web Report Viewers.
The reason for this is because we used Implicit Styling.
For the WPF Report Viewer, we will also use Implicit Styling but with the
Reporting-provided Theme references. Let’s walk through creating the WPF Report
Viewer next.
Creating the WPF Report Viewer
As with the web applications, the general process is
similar. We will add references, update the app.xaml and then create the markup
and code-behind. For reference, the entire process is detailed in How
to Add a Report Viewer to a WPF .NET Core Project.
Add Required Assembly References
There are several assemblies that need to be added for
the WPF application. Below is an outline of each and they can all be found in
the Private Telerik NuGet Feed as before (fig. 09).
- Required References
- Telerik.Reporting.Services.HttpClient
- Telerik.ReportViewer.Wpf
- Telerik.ReportViewer.Wpf.Themes
- Telerik.Windows.Controls
- Telerik.Windows.Controls.Input
- Telerik.Windows.Controls.Navigation
- Telerik.Windows.Data
Figure 09: WPF Report Viewer Assembly
References
Merge Theme Resources in App.xaml
To reuse our custom styling and add the WPF Report
Viewer, we need to update the referenced theme resources in the App.xaml (code
11).
We only need to use the Telerik.ReportViewer.Wpf.Themes dictionaries
for the control references that are used in the Report Viewer. For example, the
Telerik.Windows.Controls.GridView isn’t used by the report viewer and will use
the existing theme reference on line 10.
01.
<
Application
x:Class
=
"TWACS.WpfNetCoreCustomStyleGrid.App"
04.
StartupUri
=
"MainWindow.xaml"
>
05.
<
Application.Resources
>
06.
<
ResourceDictionary
>
07.
<
ResourceDictionary.MergedDictionaries
>
08.
<
ResourceDictionary
Source
=
"/Telerik.ReportViewer.Wpf.Themes;component/Themes/Material/System.Windows.xaml"
/>
09.
<
ResourceDictionary
Source
=
"/Telerik.ReportViewer.Wpf.Themes;component/Themes/Material/Telerik.Windows.Controls.xaml"
/>
10.
<
ResourceDictionary
Source
=
"/Telerik.Windows.Themes.Material;component/Themes/Telerik.Windows.Controls.GridView.xaml"
/>
11.
<
ResourceDictionary
Source
=
"/Telerik.ReportViewer.Wpf.Themes;component/Themes/Material/Telerik.Windows.Controls.Input.xaml"
/>
12.
<
ResourceDictionary
Source
=
"/Telerik.ReportViewer.Wpf.Themes;component/Themes/Material/Telerik.ReportViewer.Wpf.xaml"
/>
13.
</
ResourceDictionary.MergedDictionaries
>
14.
</
ResourceDictionary
>
15.
</
Application.Resources
>
16.
</
Application
>
Code Snippet 11: WPF App.xaml File
Add Namespace to the MainWindow Declaration
Since we are adding new references and will use them on
our MainWindow, we also need to include the declaration at the top of the page
(code 12). We will add Telerik.ReportViewer.Wpf and Telerik.Reporting
namespaces to the page on lines 6 and 7.
01.
<
Window
x:Class
=
"TWACS.WpfNetCoreCustomStyleGrid.MainWindow"
06.
xmlns:tr
=
"clr-namespace:Telerik.ReportViewer.Wpf;assembly=Telerik.ReportViewer.Wpf"
07.
xmlns:telerikReporting
=
"clr-namespace:Telerik.Reporting;assembly=Telerik.Reporting"
09.
xmlns:local
=
"clr-namespace:TWACS.WpfNetCoreCustomStyleGrid"
10.
mc:Ignorable
=
"d"
11.
Title
=
"Main Window"
Height
=
"800"
Width
=
"700"
>
Code Snippet 12: MainWindow.xaml Declarations
Create the Report Viewer
Control
To keep the user experience similar where the end user
selects the report from a dropdown, we have used two additional controls—the
WPF Tab control and the WPF ComboBox control (code 13 & code 14).
WPF MainWindow.xaml Markup
01.
<
Window
x:Class
=
"TWACS.WpfNetCoreCustomStyleGrid.MainWindow"
06.
xmlns:tr
=
"clr-namespace:Telerik.ReportViewer.Wpf;assembly=Telerik.ReportViewer.Wpf"
07.
xmlns:telerikReporting
=
"clr-namespace:Telerik.Reporting;assembly=Telerik.Reporting"
09.
xmlns:local
=
"clr-namespace:TWACS.WpfNetCoreCustomStyleGrid"
10.
mc:Ignorable
=
"d"
11.
Title
=
"Main Window"
Height
=
"800"
Width
=
"700"
>
12.
<
Grid
>
13.
<
telerik:RadTabControl
>
14.
<
telerik:RadTabControl.Items
>
15.
<
telerik:RadTabItem
Header
=
"Grid"
>
16.
<
telerik:RadGridView
x:Name
=
"RadGridView1"
Loaded
=
"RadGridView1_Loaded"
AutoGenerateColumns
=
"False"
IsFilteringAllowed
=
"False"
>
17.
<
telerik:RadGridView.Columns
>
18.
<
telerik:GridViewDataColumn
DataMemberBinding
=
"{Binding Id}"
IsVisible
=
"False"
IsFilterable
=
"False"
IsSortable
=
"False"
IsGroupable
=
"False"
></
telerik:GridViewDataColumn
>
19.
<
telerik:GridViewDataColumn
DataMemberBinding
=
"{Binding Name}"
Header
=
"Product Name"
IsFilterable
=
"False"
IsSortable
=
"False"
IsGroupable
=
"False"
></
telerik:GridViewDataColumn
>
20.
<
telerik:GridViewDataColumn
DataMemberBinding
=
"{Binding UnitPrice}"
Header
=
"Price"
DataFormatString
=
"{}{0:c}"
IsFilterable
=
"False"
IsSortable
=
"False"
IsGroupable
=
"False"
></
telerik:GridViewDataColumn
>
21.
<
telerik:GridViewDataColumn
DataMemberBinding
=
"{Binding Discontinued}"
Header
=
"Discontinued"
IsFilterable
=
"False"
IsSortable
=
"False"
IsGroupable
=
"False"
></
telerik:GridViewDataColumn
>
22.
<
telerik:GridViewDataColumn
DataMemberBinding
=
"{Binding UnitsInStock}"
Header
=
"Units In Stock"
IsFilterable
=
"False"
IsSortable
=
"False"
IsGroupable
=
"False"
></
telerik:GridViewDataColumn
>
23.
<
telerik:GridViewDataColumn
>
24.
<
telerik:GridViewDataColumn.CellTemplate
>
25.
<
DataTemplate
>
26.
<
StackPanel
Orientation
=
"Horizontal"
>
27.
<
telerik:RadButton
Content
=
"Edit"
Margin
=
"0,0,10,0"
/>
28.
<
telerik:RadButton
Content
=
"Cancel"
/>
29.
</
StackPanel
>
30.
</
DataTemplate
>
31.
</
telerik:GridViewDataColumn.CellTemplate
>
32.
</
telerik:GridViewDataColumn
>
33.
</
telerik:RadGridView.Columns
>
34.
</
telerik:RadGridView
>
35.
</
telerik:RadTabItem
>
36.
<
telerik:RadTabItem
Header
=
"Reports"
>
37.
<
Grid
>
38.
<
Grid.RowDefinitions
>
39.
<
RowDefinition
Height
=
"50px"
></
RowDefinition
>
40.
<
RowDefinition
></
RowDefinition
>
41.
</
Grid.RowDefinitions
>
42.
<
telerik:RadComboBox
x:Name
=
"RadComboBox1"
Grid.Row
=
"0"
Loaded
=
"RadComboBox1_Loaded"
SelectionChanged
=
"RadComboBox1_SelectionChanged"
></
telerik:RadComboBox
>
43.
<!--
44.
The Report Viewer ReportEngineConnection URI is set to the localhost and port of the TBACS.BlazorGridCustomStyle.Server project
45.
This may change for each development environment.
46.
See the launchSettings.json in that project for reference.
47.
-->
48.
<
tr:ReportViewer
x:Name
=
"reportViewer1"
Grid.Row
=
"1"
HorizontalAlignment
=
"Stretch"
EnableAccessibility
=
"False"
49.
ReportEngineConnection
=
"engine=RestService;uri=https://localhost:44395/api/reports"
>
50.
<
tr:ReportViewer.ReportSource
>
51.
<
telerikReporting:UriReportSource
Uri
=
"Dashboard.trdp"
/>
52.
</
tr:ReportViewer.ReportSource
>
53.
</
tr:ReportViewer
>
54.
</
Grid
>
55.
</
telerik:RadTabItem
>
56.
</
telerik:RadTabControl.Items
>
57.
</
telerik:RadTabControl
>
58.
</
Grid
>
59.
</
Window
>
Code Snippet 13: MainWindow.xaml Markup
WPF MainWindow.xaml.cs Code-Behind
01.
using
Newtonsoft.Json;
02.
using
System;
03.
using
System.Collections.Generic;
04.
using
System.Net.Http;
05.
using
System.Threading.Tasks;
06.
using
System.Windows;
07.
using
System.Windows.Navigation;
08.
using
TBACS.BlazorGridCustomStyle.Shared;
09.
using
Telerik.Reporting;
10.
11.
namespace
TWACS.WpfNetCoreCustomStyleGrid
12.
{
13.
///
14.
/// Interaction logic for MainWindow.xaml
15.
///
16.
public
partial
class
MainWindow : Window
17.
{
18.
public
MainWindow()
19.
{
20.
InitializeComponent();
21.
}
22.
23.
public
async Task<List
24.
{
26.
return
JsonConvert.DeserializeObject<List
27.
}
28.
29.
public
async Task<List<
string
>> GetReportFilesAsync()
30.
{
31.
/*
32.
The HttpClient RequestURI is set to the localhost and port of the TBACS.BlazorGridCustomStyle.Server
33.
This may change for each development environment.
34.
See the launchSettings.json for what to change this to
35.
*/
36.
string
json = await
new
HttpClient().GetStringAsync(
"https://localhost:44395/api/files"
);
37.
return
JsonConvert.DeserializeObject<List<
string
>>(json);
38.
}
39.
40.
private
async
void
RadComboBox1_Loaded(
object
sender, RoutedEventArgs e)
41.
{
42.
RadComboBox1.ItemsSource = await GetReportFilesAsync();
43.
RadComboBox1.SelectedIndex = 1;
44.
45.
reportViewer1.ReportSource =
new
UriReportSource
46.
{
47.
Uri = RadComboBox1.SelectedItem
as
string
48.
};
49.
}
50.
51.
private
async
void
RadGridView1_Loaded(
object
sender, RoutedEventArgs e)
52.
{
53.
RadGridView1.ItemsSource = await GetDataAsync();
54.
}
55.
56.
private
void
RadComboBox1_SelectionChanged(
object
sender, System.Windows.Controls.SelectionChangedEventArgs e)
57.
{
58.
reportViewer1.ReportSource =
new
UriReportSource
59.
{
60.
Uri = RadComboBox1.SelectedItem
as
string
61.
};
62.
}
63.
}
64.
}
Code Snippet 14: MainWindow.xaml.cs Code-Behind
The output of the new WPF application is below (fig. 10).
Figure 10: WPF Report Viewer Animation
This completes adding the WPF Report Viewer to our WPF
Application. We talked about how can use the custom theme and walked through
adding the Report Viewer. We found that the overall process is conceptually similar to adding the Report Viewers to our web applications. This is by design and will allow for our users to have some familiarity when using custom styling across products.
Conclusion
In this post, we walked through adding a Report Viewer
to our Angular, Blazor and WPF applications. Because theming across products is
designed to be simple, we were able to achieve our custom styling right out of the box
in each application. This is an important concept behind the Telerik UI and
Kendo UI suites. We like to keep everything as simple as possible.
This brings our series for styling across products to a
close. I hope the content was enjoyable, and please feel free to comment below or
create any issues in the corresponding GitHub repository as well.
Try DevCraft Today
Get started with a Telerik
DevCraft Trial today! Our DevCraft tooling is the most powerful collection
of Telerik .NET and Kendo UI JavaScript developer tools. It includes modern,
feature-rich, professionally designed UI components for web, desktop and
mobile applications; embedded reporting and report management solutions;
document processing libraries; automated testing and mocking tools.
DevCraft will arm your developers with everything needed
to deliver outstanding applications in less time and with less effort. With
award-winning technical support delivered by the developers who built the
products and a ton of resources and trainings, you can rest assured that you
have a stable provider to rely on for your everyday challenges along your
software development journey.
Source link