【问题标题】:using the FileSystemWatcher to dynamically alter the items in a combo box使用 FileSystemWatcher 动态更改组合框中的项目
【发布时间】:2015-07-10 19:30:36
【问题描述】:

好的,所以我尝试使用 FileSystemWatcher 来监视目录中的更改,然后动态更改组合框中的项目。我的 populateCb() 方法最初在加载用户控件时起作用。我在观察者更改事件中添加了一个断点,当我更改目录的内容时它会中断。所以我知道正在触发事件并且正在调用 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;
    }
}

【问题讨论】:

  • 不确定,但您可能需要将 ItemSource 设置为 null 作为 populateCb 方法的第一行。 (或使用 ObservableCollection)
  • 成功了!谢谢!太奇怪了,为什么不再次设置项目源覆盖其先前的值?我将不得不研究 ObservableCollections,这听起来像是正确的解决方案。无论如何@Steve,您应该添加一个答案,以便我可以将此问题标记为已回答。
  • 因为你没有设置新的itemsource。它是同一个对象。您已更改其内容,但对象(List)无法通知更改。设置 ItemSource = null,然后再次将其重置为同一对象会通知组合框绑定代码更改

标签: c# wpf events data-binding filesystemwatcher


【解决方案1】:

最简单的解决方案是在更改List&lt;string&gt; emails之前将ItemSource设置为null

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&lt;string&gt; 无法通知 WPF 的绑定基础结构对其元素的更改。所以清除项目,读取它们对 ComboBox 来说是完全不可见的。而是设置 ItemSource = null,然后再次重置它会通知组合框更改。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多