我有一个类,如下图所示。 我为简洁,删除了所有功能
public class PersonCollection:IList<Person>
{}
现在我又多了一个模型类,如下图所示。 AddValueCommand是ICommand的类派生再次我omiting。
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();
而我的UI看起来如下图所示
<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" />
点击按钮时,我的列表框不与新值更新。 我很想念这里。