显示所有可移动设备的ComboBox

时间:2010-07-28 07:13:12

标签: c# wpf binding combobox usb

我有一个组合框(ItemsSource =“{Binding Path = AvailableDrives}”)。

AvailableDrives属性定义如下:

 public List<DriveInfo> AvailableDrives
    {
        get
        {
            return DriveInfo.GetDrives().Where(x => x.DriveType == DriveType.Removable).ToList();
        }
    }

它工作正常,但我希望如果我插入/拔出USB设备,comboBox重新填充,而不必关闭并重新打开窗口。

我怎样才能实现这个目标?

感谢名单#

3 个答案:

答案 0 :(得分:3)

在codeproject上有一个很好的例子:Detecting USB Drive Removal in a C# Program

答案 1 :(得分:1)

简单的方法是在表单上放置一个计时器,并在事件触发时查询驱动器。然后使用新值更新组合框。

答案 2 :(得分:1)

正如奖项所述,最简单的解决方案是使用DriveDetector或类似的。 这是一个例子:

    public void InitDriveDetector()
    {
        this.dd = new DriveDetector(); // create the drive detector
        // add new event handlers
        dd.DeviceArrived += new DriveDetectorEventHandler(dd_DeviceArrived);
        dd.DeviceRemoved += new DriveDetectorEventHandler(dd_DeviceRemoved);
    }

    void dd_DeviceRemoved(object sender, DriveDetectorEventArgs e)
    {
        Debug.WriteLine("{0} removed",e.Drive);
        //Will output something like "H:\ removed"
    }

    void dd_DeviceArrived(object sender, DriveDetectorEventArgs e)
    {
        Debug.WriteLine("{0} arrived",e.Drive);
        //Will output something like "H:\ removed"
    }