首页 > 解决方案 > 如何在 Syncfusion SfListView 中绑定选中项

问题描述

我有以下剃须刀文件:

@using Syncfusion.Blazor.Lists;
@inject NavigationManager NavigationManager
@page "/main_list"

<h1>Select the items</h1>

<SfListView DataSource="@ShopItems01.ToList()" @bind-Value="@SelectedItem" TValue="ShopItem" TItem="ShopItem">
  <ListViewFieldSettings Text="Description" Id="Id" TValue="ShopItem" />
</SfListView>

<SfListView DataSource="@ShopItems02.ToList()" @bind-Value="@SelectedItem" TValue="ShopItem" TItem="ShopItem">
  <ListViewFieldSettings Text="Description" Id="Id" TValue="ShopItem" />
</SfListView>

<SfListView DataSource="@ShopItems03.ToList()" @bind-Value="@SelectedItem" TValue="ShopItem" TItem="ShopItem">
  <ListViewFieldSettings Text="Description" Id="Id" TValue="ShopItem" />
</SfListView>

@code {

  public ShopItem SelectedItem {get; set;}

  protected override async Task OnInitializedAsync()
  {
    await base.OnInitializedAsync();
    ShopItems01 = await GetItems(id: 0);
    ShopItems02 = await GetItems(id: 1);
    ShopItems03 = await GetItems(id: 2);
  }

  public void Select()
  {
    var itemId = SelectedItem.Id; //always throws null reference exception
  }    
}

DataSource 的绑定始终有效,但无法绑定所选项目。我检查了文档,他们提供了各种数据源绑定,但没有选定项目的迹象。

最接近的是某种 HTML DOM 访问,使用 @ref 并使用每个SfListView来获取其SelectedItems属性。我打赌它有效,而且我认为也可以使用一些 DOM 代码,document.getElementById()但使用 .Net 的全部意义在于避免使用这些方法。

<SfListView @ref="@SfList"
        DataSource="@DataSource"
        ShowCheckBox="true">
   <ListViewFieldSettings TValue="ListDataModel" Id="Id" Text="Text"></ListViewFieldSettings>
</SfListView>

async void OnSelect()
{
  var items = await SfList.GetSelectedItems();
  if (items.Data != null)
  {
    SelectedItems = items.Data;
    this.StateHasChanged();
  }
}

假设,如果我有 20-30 个 ListView 对象怎么办?我应该检查每个参考以找到所选项目吗?

那么,知道如何为所选项目创建工作绑定吗?

标签: htmlblazorsyncfusionblazor-webassemblysyncfusion-blazor

解决方案


ListView 组件默认不允许选择项目。在 2020 卷 3 版本中将此组件简化为 Blazor 标准时,我们已弃用所有与选择相关的 API、方法和事件。

在以下发行说明中查找详细信息。

https://blazor.syncfusion.com/documentation/release-notes/18.3.35/?type=all#listview

因此,您无法直接绑定所选项目。但是您可以使用 ListView 中的 ShowCheckbox 属性和 CheckItems 方法检查项目。

<SfButton Content="data" ID="button" OnClick="click"></SfButton>
    <SfListView @ref="@SfList"
                DataSource="@ListData"
                ShowCheckBox="true">
        <ListViewFieldSettings TValue="DataModel" Id="Id" Text="Text"></ListViewFieldSettings>
    </SfListView>
    @code{
        SfListView<DataModel> SfList;
        public List<DataModel> ListData = new List<DataModel>
         {
            new DataModel() { Text = "Jenifer",Id = "1"},
            new DataModel() { Text = "Amenda", Id = "2"},
    
        };
        async void click()
        {
           await this.SfList.CheckItems(ListData);      
        }
        public class DataModel
        {
            public string Id { get; set; }
            public string Text { get; set; }
        }
    }



推荐阅读