如何在 Blazor webassembly 应用程序中启动时初始化变量? [英] How do I initialize variables at startup in a Blazor webassembly app?
问题描述
在 UWP 中,我会在启动时以编程方式初始化显示变量,以便初始显示是我想要的,例如,基于年份值的值.我无法破解在我其他工作的 Blazor webassembly 应用程序中复制它的位置.我目前设置默认值并要求用户单击一个按钮,该按钮计算并更新我想要显示的值,然后继续.
In UWP, I would programmatically initialize display variables at startup so that the initial display was what I wanted, for example, values based on the day of the year value. I can't crack where to replicate this in my otherwise working Blazor webassembly app. I currently put up default values and ask the user to click a button, that calculates and updates to the values I want to display and on we go.
我本以为有一种标准的、简单的方法可以做到这一点,但考虑到 Blazor 部分是如何动态构建以呈现为网页的,也许不是?谢谢!
I would have thought there's a standard, easy way to do this, but given how Blazor pieces are constructed on the fly in order to render as web pages, maybe not? Thanks!
推荐答案
这不是 Blazor 特有的,但在任何类中,您都可以在组件的构造函数中创建代码/
This isn't specific to Blazor, but in any class you can create code in the constructor of your component/
这里我有一个聊天组件,我把它分解成
Here I have a Chat component, that I break up into
Chat.razor
Chat.razor.cs
通过添加与组件同名的类创建的 chat.razor.cs,然后添加单词 partial 使其成为部分类:
The chat.razor.cs you create by adding a class with the same name as your component, then add the word partial to make it a partial class:
partial class Chat : IBlazorComponent, IBlazorComponentParent, IDisposable
注意:界面仅适用于我的应用程序,我只是显示部分行.你真的需要它:
Note: The interfaces are just for my app, I am just showing the line with partial. really are you need it:
partial class Chat
然后在我的构造函数中创建:
Then in my constructor I created:
public Chat()
{
// Perform initializations for this object
Init();
}
我只是调用一个方法,你不必:
I just call a method, you don't have to:
我的初始化方法:
public void Init()
{
// do your initializations
}
或者你可以使用 OnInitializedAsync
Or you can use OnInitializedAsync
protected override async Task OnInitializedAsync()
{
// load the Categories (example)
this.Categories = await HelpCategoryService.GetHelpCategoryList()
}
或者这是我有时使用的另一个:OnAfterRender
Or here is another I use sometimes: OnAfterRender
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
...
}
}
相关文档在这里:
https://docs.microsoft.com/en-us/aspnet/core/blazor/lifecycle?view=aspnetcore-3.1
也许这会给你一些想法.不确定标准版,每个用例都不同.
Maybe that gives you some ideas. Not sure about Standard, every use case is different.
注意:我从未使用过 Blazor Web Assembly,只使用过服务器端 Blazor,所以不确定 WASM 的具体内容,但我知道构造函数适用于任何 C# 类.
Note: I have never used Blazor Web Assembly, only server side Blazor, so not sure what is specific to WASM, but I know constructors work in any C# class.
这篇关于如何在 Blazor webassembly 应用程序中启动时初始化变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!