ListView从列表绑定
本文关键字:绑定 列表 ListView | 更新日期: 2023-09-27 18:00:24
我搜索了所有的互联网,但没有找到答案。我是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>();
后来我成为了一个不错的设备列表。
在另一个类中,我想将List-In-ViewModel类绑定到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中,我已经定义了"设置"answers"获取"
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…)
我还必须吃什么?:)
在视图模型中,使用find方法设置List类型的属性,并将其与视图中的XAML绑定。即ItemSource="{Binding MyList}"
。不要忘记使用implement INotifyPropertyChanged并设置您的DataContext。。。以下是为您设置数据上下文的几种方法的链接http://paulstovell.com/blog/mvvm-instantiation-approaches
很抱歉没有完全理解你。。。
我的课在哪里搜索USB设备。我只需要一个连接的USB设备列表:
命名空间中间件{公共类USB中间件{private HidDevice[]_deviceList;public delegate void ReadHandlerDelegate(HidReport报表);
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
{类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,尤其是在不同的类和方法中。对不起,谢谢你帮我:)