1

MatMenu 携带 foreach 循环中所有列表项的最后一个实例

        @foreach (var sub in subs)
            {
             <MatButton Label="Menu" OnClick="@OnClick" RefBack="@buttonForwardRef"></MatButton>
 <MatMenu @ref="Menu" TargetForwardRef="@buttonForwardRef">
                      <MatList SingleSelection="true">
                        <MatListItem>@sub.SubName</MatListItem>
                      </MatList>
    </MatMenu>
                  }

每一行都想要不同的菜单

4

1 回答 1

2

您的问题是您buttonForwardRef在所有菜单之间共享。您是否需要每个菜单的新参考:

@using Microsoft.AspNetCore.Components

@foreach (var sub in subs)
{
    <MatButton @ref="@sub.Button2"
        Label="@sub.SubName" 
        OnClick="@( (_) => OnClick(sub.Button2, sub.Menu2, sub.SubName) )">
    </MatButton>
    <MatMenu @ref="@sub.Menu2">
        <MatList>
            <MatListItem>@sub.SubName</MatListItem>
        </MatList>
    </MatMenu>
}
<h1>@subTxt</h1>

@functions
{
    public class Sub
    {
        public string SubName {set; get;} 
        public BaseMatButton Button2 {set; get;}   // reference
        public BaseMatMenu Menu2 {set; get;}       // reference
    }

    List<Sub> subs = new List<Sub> 
    {
        new Sub() { SubName="A", Button2=null, Menu2=null },
        new Sub() { SubName="B", Button2=null, Menu2=null },
        new Sub() { SubName="C", Button2=null, Menu2=null },
    };

    string subTxt = "";

    public void OnClick(BaseMatButton button, BaseMatMenu menu, string sub)
    {
        subTxt=sub;
        menu.OpenAsync(button.Ref);        
    }

}

在blazorfiddle检查样本:

在此处输入图像描述

于 2019-08-01T12:10:00.217 回答