窗口不会更新。首次启动时,它将显示正确的数据。但是,当数据更改时,窗口将不会更新。我以这种方式进行了其他一些课程,它们可以正常工作。
XAML类:
<Window x:Class="Kwisspel.View.PlayWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Kwisspel.View"
mc:Ignorable="d"
Title="PlayWindow" Height="450" Width="800"
DataContext="{Binding Play, Source={StaticResource Locator}}">
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="57,34,0,0" TextWrapping="Wrap" Text="{Binding CurrentQuestion.Text, Mode=TwoWay}" VerticalAlignment="Top" Height="43" Width="649"/>
<ComboBox ItemsSource="{Binding CurrentQuestionAnswers}" SelectedItem="{Binding SelectedAnswer, Mode =TwoWay}" HorizontalAlignment="Left" Margin="230,239,0,0" VerticalAlignment="Top" Width="120"/>
<Button Content="Bevestig
" Command="{Binding ConfirmAnswer}" HorizontalAlignment="Left" Margin="522,270,0,0" VerticalAlignment="Top" Width="111" Height="46"/>
</Grid>
C#类:
public class PlayViewModel
{
public QuizViewModel CurrentQuiz { get; set; }
public QuestionViewModel CurrentQuestion { get; set; }
public QuestionViewModel[] CurrentQuizQuestions { get; set; }
public ObservableCollection<String> CurrentQuestionAnswers { get; set; }
public AnswerViewModel SelectedAnswer { get; set; }
public ICommand ConfirmAnswer { get; set; }
private int _Counter;
public int CorrectAnswers { get; set; }
public PlayWindow p;
public PlayViewModel(QuizViewModel currentQuiz)
{
_Counter = 0;
this.ConfirmAnswer = new RelayCommand(_ConfirmAnswer);
this.CurrentQuiz = currentQuiz;
this.CurrentQuizQuestions = CurrentQuiz.Questions.ToArray();
CurrentQuestion = CurrentQuizQuestions[_Counter];
CurrentQuestionAnswers = new ObservableCollection<string>(CurrentQuestion.Answers.Select(a => a.Answer.ToString()));
}
private void _ConfirmAnswer()
{
_Counter++;
CurrentQuestion = CurrentQuizQuestions[_Counter];
CurrentQuestionAnswers = new ObservableCollection<string>(CurrentQuestion.Answers.Select(a => a.Answer.ToString()));
}
}
答案 0 :(得分:1)
更改属性后,您的属性需要引发PropertyChanged事件。您的课程应实现INotifyPropertyChanged
/// <inheritdoc cref="INotifyPropertyChanged"/>
public partial class YourViewModel : INotifyPropertyChanged
{
/// <inheritdoc/>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Notifies that a properties value has changed.
/// </summary>
/// <param name="propertyName">The property that has changed.</param>
public virtual void NotifyPropertyChanged([CallerMemberName]string propertyName = null)
{
this.CheckForPropertyErrors();
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
,然后您的属性应如下所示:
private QuestionViewModel currentQuestion;
public QuestionViewModel CurrentQuestion
{
get
{
return this.currentQuestion;
}
set
{
this.currentQuestion = value;
this.NotifyPropertyChanged();
}
}