I've the following piece of code:
@page "somePage"
<TeamsApplication RequireAuthentication="true">
<ApplicationTemplate Context="context">
Some HTML...
@*context works here*@
</ApplicationTemplate>
</TeamsApplication>
@code{
//context doesnt work here
}
Inside ApplicationTemplate tag I can access context object instance, but can't do it in code section. Is there a way I could access that instance and its values?
CodePudding user response:
Properties normally flow down, not up. So the Context
property won't work like that. The simplest solution I could think of is an EventCallback, so that the ApplicationTemplate
sends a message to the parent that the Context is available
ApplicationTemplate.razor
[Parameter] public EventCallback<Context> ContextChanged { get; set; }
/// <summary>
/// Context was set from somewhere
/// </summary>
async Task ContextSet(Context newValue)
{
// notify anyone listening to ContextChanged
await ContextChanged.InvokeAsync(newValue);
}
Then in your page logic you listen to this event callback:
<TeamsApplication>
<ApplicationTemplate ContextChanged=HandleContextChanged>
@* todo *@
</ApplicationTemplate>
</TeamsApplication>
@code
{
/// <summary>
/// Handle event from ApplicationTemplate
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
async Task HandleContextChanged(Context context)
{
// context is now available
}
}
CodePudding user response:
You can create a function that accepts a parameter of the same type of your context Type and so you have access within that function, but the question is: what you need that context for?
If you need to create a custom component that need to have access to that context, pass it to another child component, then create a [Parameter] of type RenderFragment and so you can deal with it as you want.
You can even create a local function that renders a RenderFragment but the Razor syntax for that kind of stuff is quite akward and a bit bugged
For example I have a method like this
public RenderFragment DefaultActionTemplate(PanelAction action) =>@:@{
if (action.IsToggle) {
<div>Toggle</div>
}
else {
<div>Button</div>
}
}
;
You can do the same and use your context Type instead of my PanelAction, the concept is the same
As I told you tho, the syntax is awkward and the semicolon you see at the end, need to be on a new line and can't be next the closing curly braket see this issue: https://github.com/dotnet/aspnetcore/issues/11612