2

I have a third party Blazor WebAssembly component with a width property that I want to set based on the width of a string that will be displayed within the component. How can I write a C# function that takes the string and calculates the width that it will render as and takes into account the CSS font values? Or can this only be done in JavaScript?

EDIT: I'd basically like to do this but in my Blazor C# code: Calculate text width with JavaScript

Vy Do
  • 46,709
  • 59
  • 215
  • 313
Chris
  • 1,978
  • 3
  • 23
  • 35
  • Give an example please – Mister Magoo Sep 14 '21 at 22:48
  • Can you give an example of what you are trying to achieve - not how. Sizing things based on a single measurement taken on creation kind of breaks web sites. Imagine if your question had been rendered like that and then I zoomed or changed window size - what a mess that would be. CSS can likely help you achieve your goal, but you have not shared why you want to do it like this. – Mister Magoo Sep 15 '21 at 15:08

1 Answers1

0

I don't know if I understood the question, in case my approach is wrong I'll remove the answer.

If you add two properties to a view model class, where the second one is a getter only with the value set to the length of the first one, using a simple Length function, I think it should work.

Then you need only to assign the value to the string class property and the @viewModel.stringOneLength to the property of the component.

Clearly this approach required you set the string internal to the component from an external (parent) component or via any event based approach.

Nicola Biada
  • 2,325
  • 1
  • 8
  • 22