Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ObservableCollection更新列表_C#_Wpf_Mvvm_Time_Ticker - Fatal编程技术网

C# ObservableCollection更新列表

C# ObservableCollection更新列表,c#,wpf,mvvm,time,ticker,C#,Wpf,Mvvm,Time,Ticker,我也是WPF和MVVM的新手。我正在程序中搜索USB设备。但若我连接了一个新设备,那个么需要重新启动程序才能看到它 如何做到这一点,即立即刷新 目前,我在我的类中搜索此设备: public List<Devices> devices = new List<Devices>(); public void FindDevices() // spremeni v public bool da dobis feedback { _devic

我也是WPF和MVVM的新手。我正在程序中搜索USB设备。但若我连接了一个新设备,那个么需要重新启动程序才能看到它

如何做到这一点,即立即刷新

目前,我在我的类中搜索此设备:

public List<Devices> devices = new List<Devices>();

    public void FindDevices() // spremeni v public bool da dobis feedback 
    {


        _deviceList = HidDevices.Enumerate(VendorID, ProductID).ToArray();

...     devices.Add(new Devices()
            {
                DeviceId = nod + 1,
                ManufacturerId = deviceManufacturerstring[nod],
                ProductId = deviceProductstring[nod],
                SerialNumberId = deviceSNstring[nod],
                HardwareVersionId = "test4",
                FirmwareVersionId = "test5",
                DateOfManufaturedId = "test6"

            });
public List devices=new List();
public void FindDevices()//spremeni v public bool da dobis反馈
{
_deviceList=HidDevices.Enumerate(VendorID,ProductID).ToArray();
…设备。添加(新设备()
{
DeviceId=nod+1,
ManufacturerId=设备制造商字符串[nod],
ProductId=deviceProductstring[Node],
SerialNumberId=设备安装[nod],
HardwareVersionId=“test4”,
FirmwareVersionId=“test5”,
DateOfManufacturedId=“test6”
});
在“孔换环”中,我将设备添加到列表中。我需要“孔换环”,因为我从每个设备读取了一些数据

稍后,我将在ViewModel的列表中添加此设备:

public class Windows1ViewModel : ViewModelBase
{
    public ObservableCollection<Devices> devfuck { get; protected set; }
    List<Devices> _devicelist;

    public List<Devices> Devices
    {
        get { return _devicelist; }
        set { _devicelist = value; }
    }

    public Windows1ViewModel()
    {

        USBmiddleware cs = new USBmiddleware();
        cs.FindDevices();


        devfuck = new ObservableCollection<Devices>();


        foreach (var item in cs.devices)
        {
            devfuck.Add(item);
        }

        List<Devices> keks = cs.devices;



        NotifyPropertyChanged("devfuck");
    }


    public List<Devices> lvdevices
    {
        get { return _devicelist; }
        set { _devicelist = value; }
    }
公共类Windows1ViewModel:ViewModelBase
{
公共可观测集合devfuck{get;受保护集;}
设备列表;
公共列表设备
{
获取{return\u devicelist;}
设置{u devicelist=value;}
}
公共Windows1ViewModel()
{
USBmiddleware cs=新的USBmiddleware();
cs.FindDevices();
devfuck=新的ObservableCollection();
foreach(cs.devices中的变量项)
{
devfuck.Add(项目);
}
列出keks=cs设备;
NotifyPropertyChanged(“devfuck”);
}
公共列表设备
{
获取{return\u devicelist;}
设置{u devicelist=value;}
}
要更改什么?在何处添加INotifyPropertyChanged?或者如何解决我的问题? 请帮忙,谢谢

我的ViewModelBase

public class ViewModelBase : INotifyPropertyChanged, IDisposable
{


    protected ViewModelBase()
    {
    }



    #region DisplayName


    public virtual string DisplayName { get; protected set; }

    #endregion // DisplayName

    #region Debugging Aides


    [Conditional("DEBUG")]
    [DebuggerStepThrough]
    public void VerifyPropertyName(string propertyName)
    {
        // Verify that the property name matches a real,  
        // public, instance property on this object.
        if (TypeDescriptor.GetProperties(this)[propertyName] == null)
        {
            string msg = "Invalid property name: " + propertyName;

            if (this.ThrowOnInvalidPropertyName)
                throw new Exception(msg);
            else
                Debug.Fail(msg);
        }
    }


    protected virtual bool ThrowOnInvalidPropertyName { get; private set; }



    public event PropertyChangedEventHandler PropertyChanged;


    /// <param name="propertyName">The property that has a new value.</param>
    protected virtual void NotifyPropertyChanged(string propertyName)
    {
        this.VerifyPropertyName(propertyName);

        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }

    protected virtual void NotifyPropertyChangedAll(object inOjbect)
    {
        foreach (PropertyInfo pi in inOjbect.GetType().GetProperties())
        {
            NotifyPropertyChanged(pi.Name);
        }
    }
    public virtual void Refresh()
    {
        NotifyPropertyChangedAll(this);
    }



    public void Dispose()
    {
        this.OnDispose();
    }

    /// <summary>
    /// Child classes can override this method to perform 
    /// clean-up logic, such as removing event handlers.
    /// </summary>
    protected virtual void OnDispose()
    {
    }



    ~ViewModelBase()
    {
        string msg = string.Format("{0} ({1}) ({2}) Finalized", this.GetType().Name, this.DisplayName, this.GetHashCode());
        System.Diagnostics.Debug.WriteLine(msg);
    }


}
公共类ViewModelBase:INotifyPropertyChanged,IDisposable
{
受保护的ViewModelBase()
{
}
#区域显示名
公共虚拟字符串DisplayName{get;protected set;}
#endregion//DisplayName
#区域调试助手
[有条件的(“调试”)]
[调试步骤至]
public void VerifyPropertyName(字符串propertyName)
{
//验证属性名称是否与实数匹配,
//此对象的公共、实例属性。
if(TypeDescriptor.GetProperties(此)[propertyName]==null)
{
string msg=“无效的属性名称:”+propertyName;
if(this.ThrowOnInvalidPropertyName)
抛出新异常(msg);
其他的
调试失败(msg);
}
}
受保护的虚拟bool ThrowOnInvalidPropertyName{get;private set;}
公共事件属性更改事件处理程序属性更改;
///具有新值的属性。
受保护的虚拟void NotifyPropertyChanged(字符串propertyName)
{
这个.VerifyPropertyName(propertyName);
PropertyChangedEventHandler处理程序=this.PropertyChanged;
if(处理程序!=null)
{
var e=新的PropertyChangedEventArgs(propertyName);
处理者(本,e);
}
}
受保护的虚拟void NotifyPropertyChangedAll(对象inOjbect)
{
foreach(inOjbect.GetType().GetProperties()中的PropertyInfo pi)
{
NotifyPropertyChanged(pi.Name);
}
}
公共虚拟空刷新()
{
通知PropertyChangedall(本);
}
公共空间处置()
{
this.OnDispose();
}
/// 
///子类可以重写此方法以执行
///清理逻辑,例如删除事件处理程序。
/// 
受保护的虚拟空间OnDispose()
{
}
~ViewModelBase()
{
string msg=string.Format(“{0}({1})({2})已完成”,this.GetType().Name,this.DisplayName,this.GetHashCode());
系统.诊断.调试.写线(msg);
}
}
您需要在
Windows1ViewModel
类中实现。然后,您需要从属性设置器调用它,或者在您按照当前操作设置属性之后调用它


接下来,您应该设置一个调用
FindDevices
方法,每隔一段时间调用一次,然后从那里更新
ObservableCollection
属性。

您可以使用一个经常被调用的计时器(根据需要)来完成此操作。当然,如果您可以使用事件管理来完成此操作,它会更加性感

谢天谢地,有一种方法可以做到这一点:

var watcher = new ManagementEventWatcher();
var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE       EventType = 2");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();
如下文所述:

然后,您可以订阅该事件并调用

FindDevices()

从这里开始。

我认为当调用
FindDevices()
时,您的
devfuck
属性需要是一个
Dependency属性
?尝试添加一个调用cs.FindDevices()的计时器无论您需要多久刷新一次列表。喜欢这个变量名:-)您可以实现INotifyPropertyChanged,或者按照@Ralt的说法,使用内置属性通知的依赖属性。使用“propdp”要在VS中生成代码段,可以使用eventhandler吗?插入新设备时?谢谢。我更新了我的帖子。ViewModelBase已经vontain InotifyPropertyChanged,如何删除事件?有什么区别吗?现在,当我想调用FindDevice()时,显示错误:“错误2方法FindDevices的无重载”接受0个参数”。我必须修复什么?听起来您已经更改了FindDevice()方法,并添加了一些传递给该方法的属性…如果您有类似于
public void FindDevice(string blahblah)的内容
如果没有该参数,您无法传递它。或者,您可以通过添加默认值使参数成为可选的
public void FindDevices(string bldsa=“default”)
我添加了“object sender,EventArrivedEventArgs e”,当我删除它时,我在“new EventArrivedEventHandler(FindDevices);”中出现错误“错误2“FindDevices”匹配项没有重载d”