在 blazor 中使用 <CascadingValue> 将接口而不是具体 类 传递到 @ChildContent 的 [CascadingParameter]

Passing interfaces instead of concrete classes into @ChildContent's [CascadingParameter] using <CascadingValue> in blazor

我有 Item 实施 IItemItemContainer 实施 IItemContainer

ItemContainer.razor 我有以下内容,将其自身传递给所有 @ChildContent:

<CascadingValue Value="this">
    @ChildContent
</CascadingValue>

@code{
  List<IItem> Items;
  void AddItem(IItem item) => Items.Add(item);
  .
  .
  .
}

并且在 Item class 我有以下内容:

[CascadingParameter] public IItemContainer ItemContainer {get;set;}
protected override void OnInitialized()
{
  ItemContainer.AddItem(this);
}
RenderFragment RenderStuff => Do some rendering stuff with ItemContainer
.
.
.

假设我有以下内容:

<ItemContainer>
  <Item>
  <Item>
  <Item>
</ItemContainer>

我希望在第一个 <Item> 调用其 OnInitialized 时, <ItemContainer> 已经将自身传递给 [CascadingParameter] public IItemContainer ItemContainer {get;set;}, 所以 [CascadingParameter] public IItemContainer ItemContainer {get;set;} 不会为空, ItemContainer.AddItem(this); 将被成功调用并将 <Item> 添加到 <ItemContainer>List<IItem> Items.

如果我使用具体的 classes,即 <CascadingValue Value="this">.

的 ItemContainer 而不是 IItemContainer,这不是问题

但是,当<CascadingValue Value="this">this是接口而不是具体的class时,转换不会自动发生,并且会抛出空异常(ItemContainer not passed into级联参数)。

当我尝试使用 <CascadingValue TValue="IItemContainer" Value="(IItemContainer)this"> 转换它时,会抛出异常。

我想将接口而不是具体的 classes 传递到级联参数中。有没有办法让这个工作?

And when I try to cast it using

<CascadingValue TValue="IItemContainer" 
  Value="(IItemContainer)this">

exception will be thrown.

你不应该这样做。你还得通过this

方法如下:

ItemContainer.razor

<CascadingValue Value="this">
    @ChildContent
</CascadingValue>

@code{
  List<IItem> Items;
  void AddItem(IItem item) => Items.Add(item);
  .
  .
  .
}

Item.razor

@implements IItem
 
[CascadingParameter] public IItemContainer ItemContainer {get;set;}

protected override void OnInitialized()
{
    // Note: The first ItemContainer (left to right) is the class name,
    // the second is the name of the cascading parameter property. If the compiler
    // fail to recognize that (I guess she won't), change this property to 
    // ContainerItemSet, as for instance. Otherwise, it should work perfectly 
    // fine. 
    ((ItemContainer)(object)(ItemContainer)).AddItem(this);
}