我搜索过,但我没有找到任何方法返回一个空的IViewComponentResult.我设法做到的唯一方法是返回一个空视图.有没有更好的办法?这是我的代码:
public class ClientNavigationViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
return User.IsInRole(UserRoles.CLIENT)
? View("_ClientMenu")
: (IViewComponentResult)new EmptyResult();
}
}
Run Code Online (Sandbox Code Playgroud)
这是例外:
发生了'System.InvalidCastException'类型的异常但未在用户代码中处理
附加信息:无法将"Microsoft.AspNet.Mvc.EmptyResult"类型的对象强制转换为"Microsoft.AspNet.Mvc.IViewComponentResult".
我试图返回null,但这也行不通.有任何想法吗?编辑使它像这样工作:
public class ClientNavigationViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
if (User.IsInRole(UserRoles.CLIENT))
return View("_ClientMenu");
return new EmptyViewComponent();
}
}
public class EmptyViewComponent : IViewComponentResult
{
public void Execute(ViewComponentContext context)
{
}
public Task ExecuteAsync(ViewComponentContext context)
{
return Task.FromResult(0);
}
}
Run Code Online (Sandbox Code Playgroud) 极少数人有这样的问题,他们无法对子菜单项做出反应,因为在鼠标到达子菜单之前子菜单项关闭得太快。在底部添加了一个 GIF。我们无法重现这种行为,而且它似乎只影响极少数人。

我们使用 Hardcodet.Wpf.TaskbarIcon 来显示菜单。任何想法,将不胜感激。以下是代码片段,其中我只说明了 1 个菜单项,但其他菜单项遵循相同的逻辑:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tb="http://www.hardcodet.net/taskbar"
xmlns:local="clr-namespace:FreedomPlatform"
xmlns:converters="clr-namespace:FreedomPlatform.Converters">
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<converters:InverseBooleanConverter x:Key="InverseBooleanConverter" />
<converters:InverseAndBooleanConverter x:Key="InverseAndBooleanConverter" />
<Style TargetType="{x:Type MenuItem}">
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
<ContextMenu x:Key="FreedomTrayMenu" AutomationProperties.Name="Freedom">
<MenuItem Header="Options">
<MenuItem Header="Run on Startup" StaysOpenOnClick="True" IsCheckable="True" IsChecked="{Binding RunOnStartup}" IsEnabled="{Binding RunOnStartupModificationEnabled}" />
</MenuItem>
<Separator />
</ContextMenu>
<tb:TaskbarIcon x:Key="FreedomNotifyIcon"
IconSource="{Binding StatusIconPath}"
ContextMenu="{StaticResource FreedomTrayMenu}" MenuActivation="LeftOrRightClick" KeyUp="{Binding OnKeyUp}">
<!-- Self-assign a data context (could also be done programmatically) -->
<tb:TaskbarIcon.DataContext>
<local:StatusViewModel />
</tb:TaskbarIcon.DataContext>
</tb:TaskbarIcon>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)