我是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");
}
}
Run Code Online (Sandbox Code Playgroud)
然后在主窗口中我添加了一个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>
Run Code Online (Sandbox Code Playgroud)
这是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());
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是在点击按钮后,列表框上没有显示任何内容,原因是什么?
您询问了一个原因,而 devdigital 为您提供了解决方案,值得一提的是为什么它不起作用,以及为什么他的修复有效:
您的 mlist 已绑定到 ListBox 并且一切正常。现在您按下按钮并向列表中添加一个条目。列表框不会知道此更改,因为您的列表无法告诉您“嘿,我刚刚添加了一个新项目”。为此,您需要使用实现INotifyCollectionChanged 的 Collection ,例如 ObservableCollection。这与您OnPropertyChanged修改 MessageList 上的属性非常相似,它也会调用触发事件的 OnPropertychanged 方法PropertyChanged。数据绑定注册到该PropertyChanged事件,现在知道您何时更新属性并自动更新 UI。如果您希望自动更新集合上的 UI,则对于集合也是必要的。
| 归档时间: |
|
| 查看次数: |
3913 次 |
| 最近记录: |