【发布时间】:2020-02-09 15:06:36
【问题描述】:
我的测验问题类对象有一个 ObservableCollection。我有“下一步”按钮,并希望将窗口控件绑定到该集合中的特定问题对象。绑定似乎有效(最初正确填充了文本框),但是当我单击下一步时,它确实正确填充了我的 currQuestion 对象,文本框不会更新以显示当前问题,它会继续显示原始问题。 我已经尽可能地剥离了 xaml 和代码隐藏,以使其更易于调试,是的,我知道我应该使用 mvvm,所以让我知道这是否是问题的一部分。这是我的xml
<Window x:Class="Quiz.QuizMaintWindow"
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:Quiz"
mc:Ignorable="d"
Title="QuizMaintWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Grid Name="grd1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" MinWidth="100"/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Name="txtQuestion" Grid.Column="0" Grid.Row="0" Text="{Binding Question}"/>
<Button Name="btnNext" Grid.Column="0" Grid.Row="1" Content="Next" Margin="5" Click="btnNext_Click"/>
</Grid>
这是我的代码隐藏
public partial class QuizMaintWindow : Window
{
private clsQuestionAnswer qa; // this is the current question to be displayed
private ObservableCollection<clsQuestionAnswer> questions;
private int questionIndex = 0;
public QuizMaintWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
GetTopicQuestions();
grd1.DataContext = qa;
}
private void GetTopicQuestions()
{
questions = clsData.GetTopicQuestions(10);
qa = questions[questionIndex];
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
qa = questions[++questionIndex];
// MessageBox.Show(qa.Question);
}
}
这是问题类
public class clsQuestionAnswer: INotifyPropertyChanged
{
private int questionId;
private int topicId;
private string question;
private string answer;
private bool ignore;
public int QuestionId
{
get { return questionId; }
set
{
questionId = value;
NotifyPropertyChanged("QuestionId");
}
}
public int TopicId
{
get { return topicId; }
set
{
topicId = value;
NotifyPropertyChanged("TopicId");
}
}
public string Question
{
get { return question; }
set
{
question = value;
NotifyPropertyChanged("Question");
}
}
public string Answer
{
get { return answer; }
set
{
answer = value;
NotifyPropertyChanged("Answer");
}
}
public bool Ignore
{
get { return ignore; }
set
{
ignore = value;
NotifyPropertyChanged("Ignore");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
【问题讨论】:
-
您在更改
qa时没有更新grd1.DataContext。它不会自动发生 -
我很抱歉回答自己,但据我所知,Rufos 爵士的评论似乎不是一个答案,没有复选标记让我点击接受它,只有两个图标在他的评论的左边——向上箭头和旗帜,它仍然是这样的。它看起来就像一个无法接受的评论。看起来还是那样。我会更多地查看帮助,看看我缺少什么。
标签: c# wpf observablecollection