MVVM RaisePropertyChanged抛出InvalidCastException

问题描述 投票:0回答:1

我的ViewModel第一次打开时运行良好,第二次运行良好,尽管我的“已加载” eventToCommand似乎正在发生某些情况。当我第二次打开它时,我在RaisePropertyChanged上收到此异常:

System.InvalidCastException: 'Unable to cast object of type 'UwpApp.ViewModel.QuizTeamViewModel' to type 'UwpApp.Model.Round'.'

这与所加载的命令有关吗?

ViewModel

public QuizTeamViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;

            MessengerInstance.Register<Quiz>(this, "SelectedQuiz", quiz => Quiz = quiz);

            SelectionChangedCommand = new RelayCommand<Round>(ChangeSelectedRound);
            ViewLoadedCommand = new RelayCommand(ViewLoaded);
            ClickRankingQuizTeamCommand = new RelayCommand(OnRankingQuizTeamClick);
        }

        private void ViewLoaded()
        {
            if (Quiz == null) return;
            Rounds = new ObservableCollection<Round>(Quiz.Rounds);
            RaisePropertyChanged("Rounds");

            FillQuizTeams();
        }

        private async void FillQuizTeams()
        {
            var quizTeamsToDisplay = new ObservableCollection<QuizTeamListViewModel>();
            foreach (var quizTeam in Quiz.QuizTeams)
            {
                var team = await ApiService<Team>.GetAsync($"{StaticUri.GetUri()}/teams/quizTeam/{quizTeam.Id}");
                quizTeam.Name = team.Name;
                quizTeamsToDisplay.Add(new QuizTeamListViewModel(quizTeam, this));
            }

            QuizTeams = quizTeamsToDisplay;
            RaisePropertyChanged("QuizTeams");
        }

Xaml

    <i:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="Loaded">
            <core:InvokeCommandAction Command="{Binding ViewLoadedCommand}" />
        </core:EventTriggerBehavior>
    </i:Interaction.Behaviors>
c# .net mvvm uwp mvvm-light
1个回答
0
投票

由于某种原因,我的组合框并非总是向我的命令发送Round对象,因此,它试图将错误的对象投射到Round。

我所做的修复是将SelectionChangedCommand中的Type更改为对象,并检查RelayCommand方法是否对象是Round。

© www.soinside.com 2019 - 2024. All rights reserved.