使用 FileSystemWatcher 动态更改组合框中的项目

using the FileSystemWatcher to dynamically alter the items in a combo box

好的,所以我正在尝试使用 FileSystemWatcher 来监视目录中的更改,然后动态更改组合框中的项目。我的 populateCb() 方法最初在加载用户控件时起作用。我在 watcher changed 事件中添加了一个断点,当我更改目录的内容时它会中断。所以我知道正在触发事件并且正在调用 watcher_Changed 方法。但是我的组合框的内容没有改变...我做错了什么?

public partial class HtmlViewer : UserControl
{
    private List<string> emails = new List<string>();
    FileSystemWatcher watcher = new FileSystemWatcher("emailTemplates", "*.msg");
    public HtmlViewer()
    {
        InitializeComponent();
        populateCb();
        watcher.Changed += watcher_Changed;
        watcher.Created += watcher_Changed;
        watcher.Deleted += watcher_Changed;
        watcher.Renamed += watcher_Changed;
        watcher.EnableRaisingEvents = true;

    }

    void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        this.Dispatcher.Invoke((Action)(() =>
            {
                populateCb();
            }
            ));

    }
    private void populateCb()
    {
        emails.Clear();
        foreach(var file in Directory.EnumerateFiles("emailTemplates", "*.msg", SearchOption.AllDirectories))
        {
            emails.Add(file);
        }
        emailSelector.ItemsSource = emails;
    }
}

最简单的解决方案是在更改 List<string> emails

之前将 ItemSource 设置为空
private void populateCb()
{
    emailSelector.ItemsSource = null;
    emails.Clear();
    foreach(var file in Directory.EnumerateFiles("emailTemplates", "*.msg", SearchOption.AllDirectories))
    {
        emails.Add(file);
    }
    emailSelector.ItemsSource = emails;
}

没有它,您就不会更改以前的 ItemSource。这是同一个对象。 List<string> 无法将其元素的更改通知 WPF 的绑定基础结构。所以清除项目,读取它们对于 ComboBox 是完全不可见的。而是设置 ItemSource = null,然后再次重置它以通知组合框更改。

一个可能的(可能是更好的选择)是将您的列表更改为 ObservableCollection 能够通知更改