Search code examples
xamlmaui

MAUI ListView cannot bind ItemsSource to ObservableCollection<Type>, raises "Value does not fall within the expected range"


My ViewModel (I use CommunityToolkit.MVVM):

public partial class ViewModel : ObservableObject
{
    [ObservableProperty]
    private ObservableCollection<string> _items = new ObservableCollection<string>()
    {
        "abc", "def", "ghi"
    };

    [ObservableProperty]
    private ObservableCollection<Type> _types = new ObservableCollection<Type>()
    {
        typeof(int), typeof(string), typeof(double)
    };
}

My View:

<Grid RowDefinitions="1*,1*">
    <ListView ItemsSource="{Binding Items}" />
    <ListView ItemsSource="{Binding Types}" Grid.Row="1"/>
</Grid>

Binding Items will work, binding to Types will raise "Value does not fall within the expected range" error on Windows machine, but the code works fine in an Android Emulator.


Solution

  • I can reproduce your issue on Windows. And it turns out that the generic type parameter: T in ObservableCollection can't be defined as System.Type.

    And I notice that you open a new issue: [Windows] ListView cannot bind to ObservableCollection<System.Type> #16911, you can follow up there.

    As an alternative workaround, if you just want to display the name of the Type in ListView, you can convert it to String like below:

    public ObservableCollection<string> _types = new ObservableCollection<string>() 
    {
          typeof(int).ToString(), typeof(string).ToString(), typeof(double).ToString()
    };