在最近的几天里,我试图在blazor应用程序中读取浏览器分辨率。我正在尝试通过以下方式进行操作:[JSInvokable] Blazor Methode由JS脚本调用。
1.我的问题是:重新加载(手动刷新)页面后,宽度和高度仅显示在blazorpage中。我无法调用this.StateHasChanged(),因为我的方法是静态的。
如何调用StateHasChanged或显示新数据需要做什么?我是ASP.net等的新手,所以请尽可能包括一个代码示例;)
这是我的代码(服务器端)代码:
@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";
}
}
}
这是我的.js代码:
//------JS Code for the resize stuff incl. timer so that resize doesnt fire every pixel move
var resizeId;
window.addEventListener('resize', function () {
clearTimeout(resizeId);
resizeId = setTimeout(doneResizing, 500);
});
function doneResizing() {
var width= window.innerWidth;
var height= window.innerHeight;
alert('Width: ' +width + ' Height: ' +height);
DotNet.invokeMethodAsync('Blazor_PageResolutionJS', 'GetBrowserDimensions', width, height);
}
//^^^^^^JS Code for the resize stuff incl. timer so that resize doesnt fire every pixel move
2.这是获得浏览器分辨率以便进行UserInterface设计选择的一种好技术吗?
感谢您的阅读
您可以通过安装NuGet软件包https://www.nuget.org/packages/BlazorPro.BlazorSize/来绕过此需求
如果您仍然想自己编写代码,则可以在以下网址找到BlazorSize的源代码:https://github.com/EdCharbeneau/BlazorSize/tree/master/BlazorSize
从JavaScript调用StateHasChanged的解决方案涉及在.NET中使用[JsInvokable]方法。但是,如果您仔细查看BlazorSize的来源,您会发现,在完成对事件侦听器的处理后,需要从DOM正确删除事件侦听器,需要做大量的额外工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句