对于多选的正式示例,如果设置每页显示50行,并单击标题行中的全选复选框,则实际上表中的所有行都被选中。问题是,我只想选择当前页面中的所有行,有什么方法可以实现吗?我不想手动单击每一行。
我为您想要实现的目标创建了一个演示:https://try.mudblazor.com/snippet/GaGQENEheDggnxaW
我删除了默认的";"全选";通过使用MudTHeadRow
和MudTFootRow
组件并将IgnoreCheckbox
属性设置为true,从页眉和页脚选中复选框。还将MudTable
组件本身的CustomHeader
和CustomFooter
属性设置为true。
然后我添加了一个新的MudTh
,它显示我自己的自定义复选框。单击复选框时,我会根据表的CurrentPage
和RowsPerPage
属性向selectedItems1
哈希集添加或删除项目。
<MudTable @ref="_tableRef" CustomHeader="true" CustomFooter="true" Items="@Elements" @bind-SelectedItems="selectedItems1" MultiSelection="true" Hover="@hover">
<HeaderContent>
<MudTHeadRow IgnoreCheckbox="true">
<MudTh>
<MudCheckBox T="bool" Checked="IsSelectAllChecked" CheckedChanged="@Select"></MudCheckBox>
</MudTh>
<MudTh><MudTableSortLabel SortBy="new Func<Element, object>(x=>x.Number)">Nr</MudTableSortLabel></MudTh>
<MudTh>Sign</MudTh>
<MudTh><MudTableSortLabel InitialDirection="SortDirection.Ascending" SortBy="new Func<Element, object>(x=>x.Name)">Name</MudTableSortLabel></MudTh>
<MudTh><MudTableSortLabel SortBy="new Func<Element, object>(x=>x.Position)">Position</MudTableSortLabel></MudTh>
<MudTh><MudTableSortLabel SortBy="new Func<Element, object>(x=>x.Molar)">Mass</MudTableSortLabel></MudTh>
</MudTHeadRow>
</HeaderContent>
...
<FooterContent>
<MudTFootRow IgnoreCheckbox="true">
<MudTh>
<MudCheckBox T="bool" Checked="IsSelectAllChecked" CheckedChanged="@Select"></MudCheckBox>
</MudTh>
<MudTd colspan="5">Select All</MudTd>
</MudTFootRow>
</FooterContent>
</MudTable>
<MudText Inline="true">Selected items: @(selectedItems1==null ? "" : string.Join(", ", selectedItems1.OrderBy(x=>x.Sign).Select(x=>x.Sign)))</MudText>
@code {
private bool hover = true;
private HashSet<Element> selectedItems1 = new HashSet<Element>();
private IEnumerable<Element> Elements = new List<Element>();
private MudTable<Element> _tableRef;
private bool IsSelectAllChecked
{
get
{
var currentPage = _tableRef.CurrentPage;
var rowsPerPage = _tableRef.RowsPerPage;
var currentPageItems = _tableRef.FilteredItems.Skip(currentPage * rowsPerPage).Take(rowsPerPage);
if (!selectedItems1.Any(x => currentPageItems.Any(y => x == y)))
{
return false;
}
else
{
return true;
}
}
}
protected override async Task OnInitializedAsync()
{
Elements = await httpClient.GetFromJsonAsync<List<Element>>("webapi/periodictable");
}
private void Select()
{
var currentPage = _tableRef.CurrentPage;
var rowsPerPage = _tableRef.RowsPerPage;
var currentPageItems = _tableRef.FilteredItems.Skip(currentPage * rowsPerPage).Take(rowsPerPage);
if (!selectedItems1.Any(x => currentPageItems.Any(y => x == y)))
{
foreach(var item in currentPageItems)
{
selectedItems1.Add(item);
}
}
else
{
foreach(var item in currentPageItems)
{
selectedItems1.Remove(item);
}
}
}
}