我有一个类,如下所示。为简洁起见,我删除了所有功能
public class PersonCollection:IList<Person>
{}
现在我又多了一个 Model 类,如下所示。AddValueCommand 是派生自 ICommand 的类,我再次省略了它。
public class DataContextClass:INotifyCollectionChanged
{
private PersonCollection personCollection = PersonCollection.GetInstance();
public IList<Person> ListOfPerson
{
get
{
return personCollection;
}
}
public void AddPerson(Person person)
{
personCollection.Add(person);
OnCollectionChanged(NotifyCollectionChangedAction.Reset);
}
public event NotifyCollectionChangedEventHandler CollectionChanged = delegate { };
public void OnCollectionChanged(NotifyCollectionChangedAction action)
{
if (CollectionChanged != null)
{
CollectionChanged(this, new NotifyCollectionChangedEventArgs(action));
}
}
ICommand addValueCommand;
public ICommand AddValueCommand
{
get
{
if (addValueCommand == null)
{
addValueCommand = new AddValueCommand(p => this.AddPerson(new Person { Name = "Ashish"}));
}
return addValueCommand;
}
}
}
在主窗口中,我将我的 UI 绑定到模型,如下所示
DataContextClass contextclass = new DataContextClass();
this.DataContext = new DataContextClass();
我的用户界面如下所示
<ListBox Margin="5,39,308,113" ItemsSource="{Binding Path=ListOfPerson}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Height="20" Text="{Binding Path=Name}"></TextBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Button" HorizontalAlignment="Left" Command="{Binding Path=AddValueCommand}" Margin="233,39,0,73" />
单击按钮时,我的列表框未使用新值更新。我在这里缺少什么。