我是WPF的新手。我已经创建了一个WPF项目,并添加了以下类:
public class MessageList:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private List<string> list = new List<string>();
public List<string> MsgList
{
get { return list; }
set
{
list = value;
OnPropertyChanged("MsgList");
}
}
public void AddItem(string item)
{
this.MsgList.Add(item);
OnPropertyChanged("MsgList");
}
}
然后在主窗口中我添加了一个ListBox,下面是XAML内容:
<Window.DataContext>
<ObjectDataProvider x:Name="dataSource" ObjectType="{x:Type src:MessageList}"/>
</Window.DataContext>
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="52,44,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<ListBox Height="233" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" Margin="185,44,0,0" Name="listBox1" VerticalAlignment="Top" Width="260" ItemsSource="{Binding Path=MsgList}" />
</Grid>
以下是MainWindow.cs的源代码
public partial class MainWindow : Window
{
private MessageList mlist = null;
public MainWindow()
{
InitializeComponent();
object obj = this.DataContext;
if (obj is ObjectDataProvider)
{
this.mlist = ((ObjectDataProvider)obj).ObjectInstance as MessageList;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this.mlist.AddItem(DateTime.Now.ToString());
}
}
我有一个问题,就是当我点击按钮后,列表框上没有显示任何内容,这是什么原因?