如何从Xamrin.Form中的ListView和ViewModel ObservableRangeCollection中删除项目?

时间:2018-02-23 08:14:31

标签: c# listview xamarin.forms mvvm-light

我想从Xamrin.Form中的ListView和ViewModel ObservableRangeCollection中删除项目。

EmployeeResultsPage

<ListView x:Name="EmployeeResultsListView"
          ItemsSource="{Binding EmployeeResults}"
          RowHeight="200"
          IsPullToRefreshEnabled="true"
          RefreshCommand="{Binding RefreshDataCommand}"
          IsRefreshing="{Binding IsRefreshingData, Mode=OneWay}"
          ItemAppearing="Employee_ItemAppearing"
    <ListView.ItemTemplate>
        <DataTemplate>
            <local:EmployeeResultViewCell />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

EmployeeResultViewModel

[ImplementPropertyChanged]
public class EmployeeResultsViewModel : ViewModelBase
{
    private async Task LoadEmployee()
    {
        EmployeeResults = GetDataUsingAPI(); //15 records per call
        OnDeleteEmployeeCommand = new RelayCommand<object>(async (model) => await DeleteEmployee(model));
    }

    public ObservableRangeCollection<ExtendedEmployee> EmployeeResults { get; set; }

    public string EmployeePhotoUrl { get; set; }
    public string EmployeeName { get; set; }
    public ICommand OnDeleteMessageCommand { get; set; }
    private async Task DeleteEmployee(object obj)
    {
        //get object here
    }
}

EmployeeResultViewCell

<ViewCell.ContextActions>
    <MenuItem
        Text="Delete"
        IsDestructive="true"
        Command="{Binding Path=BindingContext.OnDeleteEmployeeCommand, Source={x:Reference EmployeeResultsPage}}"
        CommandParameter="{Binding .}"/>
</ViewCell.ContextActions>
<ViewCell.View>
    <Grid RowSpacing="0" ColumnSpacing="0" VerticalOptions="Center" HeightRequest="150">
        <Image x:Name="EmployeeImage" Grid.Column="0" HeightRequest="150" WidthRequest="150"
        Source="{Binding EmployeePhotoUrl}" />
        <Label Text="{Binding EmployeeName}" FontSize="18" TextColor="Grey"/>
    </Grid>
</ViewCell.View>

CS档案

public partial class EmployeeResultViewCell : CustomViewCell
{
    public EmployeeResultViewCell()
    {
        InitializeComponent();
    }

    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();
        var employee = (BindingContext as ExtendedEmployee);
    }

}

已更改:删除点击事件并添加绑定。

1 个答案:

答案 0 :(得分:1)

使用MVVM,您不使用事件,而是在视图模型中可以绑定到视图命令的命令。获得所需内容的最MVVM方法是向您的单元格添加ICommand可绑定属性

public partial class EmployeeResultViewCell : CustomViewCell
{
    /// <summary>
    ///   The <see cref="DeleteCommand" /> bindable property.
    /// </summary>
    public static readonly BindableProperty DeleteCommandProperty = BindableProperty.Create(nameof(SealCheckListPage.DeleteCommand), typeof(ICommand), typeof(SealCheckListPage), default(ICommand));

    /// <summary>
    ///   Gets or sets the DeleteCommand that is called when we'd like to delete an employee.
    /// </summary>
    public ICommand DeleteCommand
    {
        get => (ICommand)this.GetValue(SealCheckListPage.DeleteCommandProperty);

        set => this.SetValue(SealCheckListPage.DeleteCommandProperty, value);
    }

    private void MenuItemDelete_Clicked(object sender, System.EventArgs e)
    {
        DeleteCommand?.Execute(BindingContext);
    }
}

现在您可以将DeleteCommand绑定到您的viewmodel

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate>
            <local:EmployeeResultViewCell DeleteCommand="{Binding BindingContext.DeleteCommand, Source={x:Reference Page}}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

请注意,包含ListView的页面必须包含x:Name="Page"才能正确绑定命令。不可否认,以这种方式绑定命令并不是最佳选择,但据我所知,这是我们能做的最好的事情,MVVM明智。

您要做的最后一件事是向您的viewmodel添加ICommand属性

public class EmployeeResultsViewModel : ViewModelBase
{
    private async Task LoadEmployee()
    {
        EmployeeResults = GetDataUsingAPI(); //15 records per call

        DeleteCommand = new Command<ExtendedEmployee>(OnDelete);
    }

    public ICommand DeleteCommand { get; }

    private void OnDelete(ExtendedEmployee employee)
    {
        // delete the employee from the collection
    }

    /* ... */
}

现在,当您的单元格收到事件时,它会执行命令,该命令绑定到viewmodel中的命令。执行此命令时,它会执行传递的委托OnDelete,您可以在其中访问要从中删除ExtendedEmployee的集合。