Blazor:如何在JSInterOP调用后调用StateHasChanged尝试通过JS调整大小事件调整大小后尝试将BwoserResolution获取到Blazor App?

问题描述

最近几天,我试图在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";
        }
    }
}

这是我的.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/

来绕过此需求

如果您仍然想自己编写代码,可以在https://github.com/EdCharbeneau/BlazorSize/tree/master/BlazorSize处找到BlazorSize的源代码

从JavaScript调用StateHasChanged的解决方案涉及在.NET中使用[JsInvokable]方法。但是,如果仔细查看BlazorSize的来源,您会发现,在完成对事件侦听器的操作后,从DOM正确删除事件侦听器还需要做大量的工作。