MVVM RaisePropertyChanged引发InvalidCastException

时间:2019-12-29 21:49:57

标签: c# .net mvvm uwp mvvm-light

我的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>

0 个答案:

没有答案