This is in a new blazor project template in visual studio.
Index.razor:
@code
{
bool test = false;
}
Program.cs:
NewProject.Pages.Index.test = true;
This throws "an object reference is required for the non-static field, method, or property "Index.test"". But I'm not sure how to reference NewProject.Pages.Index as an object because I can't find where it is instantiated. How do I get the object reference for the page that blazor displays in the browser?
The @code
section in a .razor file is part of the class for that component. Its properties and fields are treated the same as properties and fields of an ordinary class. The default in C# for properties and fields is internal
and instance--you'd have to have an instance of the Index component. But we almost never would create references of component instances manually; the @Page
routing system or parent components allow the runtime to create instances for us, so we'd never have a reference to a component instance directly.
So, if you want to access items inside the component without having an instance of the component (since you are calling it presumably from Program.Main
), you'd have to mark it public static
like this:
@code
{
public static bool Test {get; set;} = false;
}
Then that single value would be available anywhere; you could access it from Program.cs via NewProject.Pages.Index.Test
, as it would...but I'd question why you want to do this. Care to provide any broader context on what you are trying to do here so I can help with the "real" issue at hand here?