Blazor MatMenu在foreach循环的所有菜单中取最后一个值

时间:2019-07-31 05:44:03

标签: blazor matblazor

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>
                  }

Everey行需要区别菜单

1 个答案:

答案 0 :(得分:1)

您的问题是您正在所有菜单之间共享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处检查样品:

enter image description here