Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

Blazor WebAssembly JSInvokable Binding - how to update screen?

I have a situation where I am listening for scroll events in JS on the page, when the scroll event is triggered it calls a C# method which is JSInvokable to store the current scroll position in a variable.

I want to be able to display this value on the page as it changes (mainly for development). But the JSInvokable method stores the value correctly but the two way binding is not updated.

The below is a pseudo example:

<div>Current Scroll Position: @scrollPosition.ToString()</div>


@code{

long scrollPosition = 0;

[JSInvokable("OnScroll")]
public void OnScroll(string index)
{
    int.TryParse(index, out var topIndex);
    scrollPosition = topIndex;
}
}

I was hoping that when the scrollPosition variable was updated from the JS calling the JSInvokable method, it would also update the DOM entry.

I realise I could do this all via JS but just wanted to try the binding as an example. I am not using any input fields for this but just a variable being displayed in the DOM and updated.

Am I doing this wrong?

Thank you

question from:https://stackoverflow.com/questions/65644309/blazor-webassembly-jsinvokable-binding-how-to-update-screen

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try to use:

InvokeAsync(() => { StateHasChanged(); });

Do it like this:

[JSInvokable("OnScroll")]
public async Task OnScroll(string index)
{
    int.TryParse(index, out var topIndex);
    scrollPosition = topIndex;
    await InvokeAsync(() => { StateHasChanged(); });
 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...