Search code examples
c#wpfmvvmprism

InvalidCastException when removing item from ObservableCollection


I have a prism View with a ListView, a Button and a ObservableCollection. When i remove an item from that collection i get a InvalidCastException on the Remove() call. What am i doing wrong?

View.xaml:

<ListView Name="lvSomeEntities" SelectionMode="Single" ItemsSource="{Binding SomeEntityList}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <prism:InvokeCommandAction Command="{Binding LvSelectionChangedCommand}" CommandParameter="{Binding ElementName=lvSomeEntities, Path=SelectedItem}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ListView>

<Button Name="button" Content="Delete SomeEntity" Command="{Binding DeleteSomeEntityCommand}" CommandParameter="{Binding ElementName=lvSomeEntities, Path=SelectedItem}"/>

ViewModel.cs:

public DelegateCommand<SomeEntity> DeleteSomeEntityCommand { get; private set; }

private ObservableCollection<SomeEntity> _someEntityList = new ObservableCollection<SomeEntity>();
public ObservableCollection<SomeEntity> SomeEntityList
{
    get { return _someEntityList; }
    set { SetProperty(ref _someEntityList, value); }
}

public ViewModel()
{
    DeleteSomeEntityCommand = new DelegateCommand<SomeEntity>(DeleteSomeEntity, DeleteSomeEntityEnabled);
}

private void DeleteSomeEntity(SomeEntity someEntity)
{
    SomeEntityList.Remove(someEntity);//here i get the InvalidCastException
}

private bool DeleteSomeEntityEnabled(SomeEntity someEntity)
{
    return someEntity != null;
}

SomeEntity.cs:

public class SomeEntity
{
    public SomeEntity(int id, string name)
    {
        Id = id;
        Name = name;
    }

    public int Id { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return Id + " " + Name;
    }
}

Exception Message:

System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Controls.SelectionChangedEventArgs' to type 'SomeEntity'.'

The funny part is, when the exception is thrown and i check the content of the ObservableCollection in the debugger, the item is actually removed.


Solution

  • Thanks for the comments. I removed now the <i:Interaction.Triggers>... </i:Interaction.Triggers> and binded the SelectedItem of my ListView to a property as suggested from @Haukinger. To replace the LvSelectionChanged i now call this method from the setter of the property. That works but does not explain the exception i had.