如何解决如何从位置/ URL /路线获取组件类型
场景:
我有一个带有基本路由的Blazor服务器端应用程序,导航后,我需要检查当前页面是否实现了特定的界面。 例如:
NavigationService.LocationChanged += (sender,args) =>
{
Type componentType = GetComponetFromLocation(args.Location);
if (!componentType.GetInterfaces().Contains(typeof(PageBase)) {
}
}
问题:
如何获取当前或特定网址/位置的组件类型?
解决方法
不确定要达到的目标,但这可能会有所帮助:
App.razor
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<CascadingValue Value="@routeData.PageType" Name="PageType" >
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</CascadingValue>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry,there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
随着页面类型现在作为级联值传递,您可以:
@if(!PageType.IsSubclassOf(typeof(PageBase)))
{
<div> ... </div>
}
@if(PageType.GetInterface("PageBase") == null)
{
<div> ... </div>
}
@code {
[CascadingParameter(Name="PageType")]
public Type PageType { get; set; }
}
我在这里使用了两个@If
块,因为您的问题是关于接口的,但是您的示例似乎是关于基本类型的。其中之一应该满足您的需求。
您可以在MainLayout组件中添加OnParametersSet方法...
还添加:@using System.Reflection;
protected override void OnParametersSet()
{
// Get the Component Type from the route data
var component = (this.Body.Target as RouteView)?.RouteData.PageType;
// Get a list of all the interfaces implemented by the component.
// It should be: IComponent,IHandleEvent,IHandleAfterRender,// Unless your routable component has derived from ComponentBase,// and added interface implementations of its own
var allInterfaces = component.GetInterfaces();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。