【发布时间】:2016-03-08 09:06:40
【问题描述】:
所以我有一个 WPF c# 项目,在一个用户控件中,我有一个列表,它通过 DataTemplateSelector 设置集合的显示。那些包含一些简单字符串和整数的数据绑定对象,以及一个称为 Answers 的可观察字符串集合。我已经使用所需的 PropertyChangedEventHandler 和函数在对象内部实现了 INotifyPropertyChanged。
所以,这里是位于 datatempate 中的 xaml 的 sn-p,用于显示列表项
<DataGrid x:Name="AnswersListBox" HorizontalAlignment="Stretch" Grid.Column="3" Grid.Row="3" Grid.ColumnSpan="2" ItemsSource="{Binding Answers}"
AutoGenerateColumns="False" Margin="10,10,10,10" CanUserResizeRows="False" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=DataContext,
RelativeSource={RelativeSource Self}, Mode=TwoWay}" Header="Possible Answers"
Width="130" IsReadOnly="False" CanUserResize="False" CanUserSort="False" CanUserReorder="False" MaxWidth="130"/>
</DataGrid.Columns>
</DataGrid>
显示工作数据绑定对象的图像
我的问题是,显示答案的数据网格(当前重复“一个单词”)不会更新... 我用可编辑的列表视图和带有文本框的列表框尝试了很多变体,但是这个数据网格是我得到的最接近的,除了它不会在那个可观察的集合中保留一个编辑的值
编辑以添加更多代码
这是 ObserverableCollection
namespace CRUDeBuilder.chunkProtos
{
public class MultiChoice : Question
{
/// <summary>
/// this is a type of question that holds a statement and several answers
/// </summary>
private ObservableCollection<string> answers = new ObservableCollection<string>();
private int correctAnswer = 0;
private bool randomise = false;
public MultiChoice()
{
base.QuestionType = "multiChoice";
}
public ObservableCollection<string> Answers
{
get
{
return answers;
}
set
{
answers = value;
base.NotifyPropertyChanged("Answers");
}
}
// ive just chopped off bits here
INotifyPropertyChanged 的实现在 Multichoice:Question 的基类中,是
public abstract class Question : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
将项目添加到答案 observablecollection 的代码
private void addAnswerBtn_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
Question question = button.DataContext as Question;
//Console.WriteLine("clicking add answer button");
if (question is MultiChoice)
{
Console.WriteLine("is a multichoice ");
((MultiChoice)question).addAnswer("a word");
//((MultiChoice)question).Answers.Add("a word");
// both of these add, but I added the custom version to check
}
else
{
Console.WriteLine("is NOT a multichoice");
}
}
我看不出我错过了什么才能将这些编辑后的答案设置为数据
【问题讨论】:
-
向我们展示您的 ObservableCollection 定义以及用于更新它的代码。信息如此之少,我们无能为力。