Search code examples
c#wpfxamlbindingmvvmcross

MvxObservableCollection AddRange


I have viewmodel (with Fody INPC):

public sealed class ItemsViewModel : MvxViewModel, IMvxNotifyPropertyChanged
{
    private readonly IItemsService itemsService;

    public MvxObservableCollection<Item> ItemsCollection { get; private set; }
    public IMvxCommand GetItemsCommand { get; private set; }

    private async void GetItemsAsync()
    {
        var items = await itemsService.GetItemsAsync();
        ItemsCollection.Clear();
        ItemsCollection.AddRange(items);
    }

    public ItemsViewModel(IItemsService itemsService)
    {
        this.itemsService = itemsService;
        ItemsCollection = new MvxObservableCollection<Item>();
        GetItemsCommand = new MvxCommand(() => GetItemsAsync());
    }
}

AddRange(items) work fine. Later, I add view for this viewmodel:

<views:MvxWpfView x:Class="MyApp.ItemsView"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:views="clr-namespace:MvvmCross.Platforms.Wpf.Views;assembly=MvvmCross.Platforms.Wpf">

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <Button Content="Get Items" Command="{Binding GetItemsCommand}"/>

    <ListView Grid.Row="1" ItemsSource="{Binding ItemsCollection}"/>
</Grid>

and it's code behind:

[MvxViewFor(typeof(ItemsViewModel))]
partial class ItemsView
{
    public DocumentTypeEditorView()
    {
        InitializeComponent();
    }
}

Now, when I click button, I get error "Range actions are not supported." When I remove ListView from xaml, all works fine. I can change ListView to DataGrid or another list control - error will be the same!

I want to know, how can I bind my view to MvxObservableCollection ?


Solution

  • What if you add the items to the source collection one by one yourself?:

    private async void GetItemsAsync()
    {
        var items = await itemsService.GetItemsAsync();
        ItemsCollection.Clear();
        foreach (var item in items)
            ItemsCollection.Add(item);
    }
    

    ...or re-set the source property to a new collection:

    private async void GetItemsAsync()
    {
        var items = await itemsService.GetItemsAsync();
        ItemsCollection = new MvxObservableCollection<Item>(items);
    }
    

    Apparently "range actions are not supported" for a data-bound MvxObservableCollection.