为什么 ListBox 不能显示绑定的 ItemsSource?

3

我是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());
        }
    }

我有一个问题,就是当我点击按钮后,列表框上没有显示任何内容,这是什么原因?

3个回答

6

6

您询问了一个原因,而devdigital给出了解决方案,值得一提的是为什么它不起作用,以及他的修复为什么有效:

您的mlist绑定到ListBox上,并且一切正常工作。现在您按下按钮并将条目添加到列表中。但是,列表框不会知道这种更改,因为您的列表无法告诉“嘿,我刚刚添加了一个新项目”。为了做到这一点,您需要使用实现INotifyCollectionChanged的集合,如ObservableCollection。这与您的OnPropertyChanged非常相似,如果您修改了MessageList上的属性,则还会调用OnPropertychanged方法,该方法触发PropertyChanged事件。数据绑定注册到PropertyChanged事件,现在知道您何时更新了属性,并自动更新UI。如果要对集合进行自动UI更新,则需要执行相同的操作。


2
罪魁祸首是string项。由于string项是原始类型,当您执行OnPropertyChanged时,它们不会刷新列表框上的绑定。要么使用可观察集合,要么在button1_Click()函数中调用此函数...
  listBox1.Items.Refresh();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接