列表

时间:2015-06-29 13:44:52

标签: c# wpf listview mvvm

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

我在一个类中定义了一个方法,在那里我搜索USB设备(在另一个.dll库的帮助下):

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

后来我成了很好的设备列表。

在另一个类中,我想将ViewModel类中的List绑定到ListView中。怎么做?我还必须启动方法来查找我的设备“FindDevices”。

我的XAML ListView如果定义如此:

<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>

所以定义了ItemsSource。 INotifyPropertyChanged我已经定义了“ViewModelBase.cs”:

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

}

同样在Devices.cs中,我已经将“set”定义为“get”

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

(+对于ManufacturerId,ProductId,SerialNumberId,HardwareVersionId,FirmwareVersionId,...)

我还必须拥有什么? :)

2 个答案:

答案 0 :(得分:0)

在viewmodel中,使用find方法设置List类型的属性,并在视图中将其与XAML绑定。即。 ItemSource="{Binding MyList}"。别忘了使用工具INotifyPropertyChanged并设置你的DataContext ... 这里有几种为您设置datacontext的方法的链接 http://paulstovell.com/blog/mvvm-instantiation-approaches

答案 1 :(得分:0)

很抱歉完全不理解你......

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

命名空间中间件 {     公共类USBmiddleware     {         private HidDevice [] _deviceList;         public delegate void ReadHandlerDelegate(HidReport report);

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


}

}

和PageViewModel我想把列表加载到我的ListView

namespace ViewModel

{     class Page2ViewModel:PageViewModelBase     {

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

}

}

如何立即返回列表?然后绑定到ListView?也许我是傻瓜,但直到现在我还没有使用这么多List,特别是在不同的类和方法中。对不起,感谢帮助我:)