nog*_*ood 4 c# window-resize blazor blazor-jsinterop
在过去的几天里,我试图在我的 blazor 应用程序中读出浏览器分辨率。我尝试这样做:[JSInvokable] Blazor Methode 由 JS 脚本调用。
1.我的问题是:宽度和高度仅在我重新加载(手动刷新)页面后显示在我的blazorpage中。我无法调用 this.StateHasChanged() 因为我的方法是静态的。
我如何调用 StateHasChanged 或者我需要做什么才能显示新数据?我对 ASP.net 等还很陌生,所以如果可能的话请包含一个代码示例;)
这是我的 Code blazor (服务器端)代码:
@page "/"
@inject IJSRuntime jsRuntime
<h1>Window Dimensions</h1>
<p>Window Width: @Width</p>
<p>Window Height: @Height</p>
<p>@DebugString</p>
@code {
public static int Width;
public static int Height;
public static string DebugString;
[JSInvokable]
public static async Task GetBrowserDimensions(int width, int height)
{
Width = width;
Height = height;
if (Width < 600)
{
DebugString = "small_UI";
}
if (Width >= 600)
{
DebugString = "big_UI";
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 .js 代码:
@page "/"
@inject IJSRuntime jsRuntime
<h1>Window Dimensions</h1>
<p>Window Width: @Width</p>
<p>Window Height: @Height</p>
<p>@DebugString</p>
@code {
public static int Width;
public static int Height;
public static string DebugString;
[JSInvokable]
public static async Task GetBrowserDimensions(int width, int height)
{
Width = width;
Height = height;
if (Width < 600)
{
DebugString = "small_UI";
}
if (Width >= 600)
{
DebugString = "big_UI";
}
}
}
Run Code Online (Sandbox Code Playgroud)
2. 这是获取浏览器分辨率以便做出用户界面设计选择的可行技术吗?
感谢您的阅读
您可以通过安装 NuGet 包来绕过此需求https://www.nuget.org/packages/BlazorPro.BlazorSize/
如果您仍然有兴趣自己编写代码,可以在https://github.com/EdCharbeneau/BlazorSize/tree/master/BlazorSize找到 BlazorSize 的源代码
从 JavaScript 调用 StateHasChanged 的解决方案涉及使用 .NET 中的 [JsInvokable] 方法。但是,如果您查看 BlazorSize 的源代码,您会发现在使用完事件侦听器后,需要做很多额外的工作才能从 DOM 中正确删除事件侦听器。
| 归档时间: |
|
| 查看次数: |
2166 次 |
| 最近记录: |