C# 列表中的ListView绑定

C# 列表中的ListView绑定,c#,wpf,listview,mvvm,C#,Wpf,Listview,Mvvm,我在互联网上到处搜索,但没有找到答案。我是MVVM新手,也是WPF新手 我在一个类中定义了方法,在该类中我搜索USB设备(借助另一个.dll库): (+用于制造商ID、产品ID、序列号ID、硬件版本ID、固件版本ID等) 我还必须吃什么?:) 在viewmodel中,使用find方法设置List类型的属性,并在视图中将其与XAML绑定。例如,ItemSource=“{Binding MyList}”。不要忘记使用ImplementiNotifyPropertyChanged并设置DataCont

我在互联网上到处搜索,但没有找到答案。我是MVVM新手,也是WPF新手

我在一个类中定义了方法,在该类中我搜索USB设备(借助另一个.dll库):

(+用于制造商ID、产品ID、序列号ID、硬件版本ID、固件版本ID等)


我还必须吃什么?:)

在viewmodel中,使用find方法设置List类型的属性,并在视图中将其与XAML绑定。例如,
ItemSource=“{Binding MyList}”
。不要忘记使用ImplementiNotifyPropertyChanged并设置DataContext。。。 这里有一个链接,指向为您设置datacontext的几种方法
很抱歉不能完全理解您的意思

我的班级在哪里搜索USB设备。我只需要一个已连接USB设备的列表:

命名空间中间件 { 公共类usbmidware { 私有设备[]设备列表; 公共委托无效ReadHandlerDelegate(HidReport报告)

{ 类Page2ViewModel:PageViewModelBase {

publicpage2viewmodel()
{
Heading=“第2页”;
//新的usbmidware().FindDevices();
List devices=USBmiddleware.MyWildDevices();
}
公共覆盖无效按钮继续单击()
{
Page3ViewModel vm=新的Page3ViewModel();
第3页p3=新的第3页();
p3.DataContext=vm;
Navigator.NavigationService.Navigate(p3);
}
}
}


现在如何返回列表?以后如何绑定到ListView?也许我很笨,但直到现在我才使用这么多列表,特别是在不同的类和方法中。很抱歉,感谢您的帮助:)

您使用
{Binding}绑定它们
xaml标记扩展。是的,您必须启动方法来查找您的设备:)将ListView的ItemSource属性绑定到{Binding}DataContext?请举个例子:)您必须记住将视图的DataContext设置为viewmodel的一种方式,在视图的代码后面,这个。DataContext=new MyViewModel();这会将视图的datacontext设置为视图模型的一个实例。您也可以通过XAML执行此操作,如果您愿意,可以使用谷歌搜索。这基本上会告诉您的视图要绑定到什么(视图模型)以及为什么我必须“绑定”“ItemsSource和DataContext”在我搜索设备的第一个类中,我有一个我想要运行的循环。但是我的ViewModel没有找到它,除非我将第一个类中的方法更改为静态。但是我的.dll库有问题,这给了我一个错误“非静态字段、方法或属性需要对象引用”.怎么办?:)如果看不到整个代码,很难说。听起来你只需要先实例化(创建)一个类的新实例。例如,MyClass MyClass=new MyClass()。然后,MyClass.FindDevices();听起来您正在使用的DLL不希望它是静态的,所以您必须有一个对象引用,即您刚刚创建的myClass。
public void FindDevices()
    {
        _deviceList = HidDevices.Enumerate(VendorID, ProductID).ToArray();

        String[] deviceSNstring = new String[_deviceList.Length];
        String[] deviceManufacturerstring = new String[_deviceList.Length];
        String[] deviceProductstring = new String[_deviceList.Length];

        List<Devices> devices = new List<Devices>();
<ListView Name="DeviceGrid" Grid.Row="2" Margin="15,10,15,35" ItemsSource="{Binding lvDevices}">
        <ListView.View>
            <GridView x:Name="gridDevices">
                <GridViewColumn x:Name="DeviceId" Header="DeviceId" DisplayMemberBinding="{Binding DeviceId}" Width="50"/>
                <GridViewColumn x:Name="ManufacturerId" Header="ManufacturerId" DisplayMemberBinding="{Binding ManufacturerId}" Width="150"/>
                <GridViewColumn x:Name="ProductId" Header="ProductId" DisplayMemberBinding="{Binding ProductId}" Width="150"/>
                <GridViewColumn x:Name="SerialNumberId" Header="SerialNumberId" DisplayMemberBinding="{Binding SerialNumberId}" Width="150"/>
                <GridViewColumn x:Name="HardwareVersionId" Header="HardwareVersionId" DisplayMemberBinding="{Binding HardwareVersionId}" Width="130"/>
                <GridViewColumn x:Name="FirmwareVersionId" Header="FirmwareVersionId" DisplayMemberBinding="{Binding FirmwareVersionId}" Width="130"/>
                <GridViewColumn x:Name="DateOfManufaturedId" Header="DateOfManufaturedId" DisplayMemberBinding="{Binding DateOfManufaturedId}" Width="130"/>
            </GridView>
       </ListView.View>
public class ViewModelBase : INotifyPropertyChanged, IDisposable
{
    #region Constructor

    protected ViewModelBase()
    {
    }

    #endregion // Constructor

    #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; }

    #endregion // Debugging Aides

    #region INotifyPropertyChanged Members

    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);
    }
    #endregion // INotifyPropertyChanged Members

    #region IDisposable Members

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

    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);
    }


    #endregion // IDisposable Members

}
public class Devices : ViewModelBase
{

    private int deviceid;
    private string manufacturerid;
    private string productid;
    private string serialnumberid;
    private string hardwareversionid;
    private string firmwareversionid;
    private string dateofmanufacturedid;

    public int DeviceId
    {
        get
        {
            return deviceid;
        }
        set
        {
            deviceid = value;
            NotifyPropertyChanged("DeviceId");
        }
    }
    private const int VendorID = 0x453;
    private const int ProductID = 0x3FG;

    private static readonly int[] SupportedDeviceGrid = new[] { VendorID, ProductID };

    int nod; // number of devices



    public void FindDevices()
    {


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

        String[] deviceSNstring = new String[_deviceList.Length];
        String[] deviceManufacturerstring = new String[_deviceList.Length];
        String[] deviceProductstring = new String[_deviceList.Length];

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

        List<Devices> mydevices = MyWildDevices();


        for (nod = 0; nod < _deviceList.Length; nod++)
        {
            bool boolSerialNumber = false;
            byte[] dataSerialNumber;
            boolSerialNumber = _deviceList[nod].ReadSerialNumber(out dataSerialNumber);

            bool boolManufacturer = false;
            byte[] dataManufacturer;
            boolManufacturer = _deviceList[nod].ReadManufacturer(out dataManufacturer);

            bool boolProduct = false;
            byte[] dataProduct;
            boolProduct = _deviceList[nod].ReadProduct(out dataProduct);

            if (boolSerialNumber == true)
            {
                deviceSNstring[nod] = FromHexString((String.Join("", dataSerialNumber.Select(d => d.ToString("X2")))));
            }
            else
            {
                deviceSNstring[nod] = "Error by Reading SerialNumber of device";
            }

            if (boolManufacturer == true)
            {
                deviceManufacturerstring[nod] = FromHexString((String.Join("", dataManufacturer.Select(d => d.ToString("X2")))));
            }
            else
            {
                deviceManufacturerstring[nod] = "Error by Reading ManufacaturerID of device";
            }

            if (boolProduct == true)
            {
                deviceProductstring[nod] = FromHexString(String.Join("", dataProduct.Select(d => d.ToString("X2"))));
            }
            else
            {
                deviceProductstring[nod] = "Error by Reading ProductID of device";
            }

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

            });
        }

    }

    public static List<Devices> MyWildDevices()
    {

        List<Devices> DeviceList = new List<Devices>();

        return DeviceList;
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes);
    }

    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString();
    }


}
namespace ViewModel
    public Page2ViewModel()
    {
        Heading = "Page 2";

        //new USBmiddleware().FindDevices();

        List<Devices> devices = USBmiddleware.MyWildDevices();
    }

    public override void ButtonContinueClick()
    {
        Page3ViewModel vm = new Page3ViewModel();
        Page3 p3 = new Page3();
        p3.DataContext = vm;
        Navigator.NavigationService.Navigate(p3);
    }

}