I have a listview with two columns Devicename and DeviceAddress. I have maintained an observablecollection for the listview. I am using MVVM pattern.
View:
<ListView Height="100" ItemsSource="{Binding I2CDeviceList}" SelectedItem="{Binding SelectedI2CAddress, Mode=TwoWay}" Name="I2cDeviceList">
<ListView.View>
<GridView>
<GridViewColumn Header="I2C Device" Width="190" DisplayMemberBinding="{Binding I2CDevName}" />
<GridViewColumn Header="I2C Device Address" Width="203" DisplayMemberBinding="{Binding I2CDeviceAddress}" />
</GridView>
</ListView.View>
</ListView>
Both I2CDevicename and I2CDeviceAddress are part of my model class.
ViewModel:
public ObservableCollection<ModelClass> I2CDeviceList
{
get { return _I2CDeviceList; }
set
{
_I2CDeviceList = value;
NotifyPropertyChanged("I2CDeviceList");
}
}
The items to be added inside DeviceName & DeviceAddress respectively are:
{ T("Other"), T("0x00")},
{ T("TI Codec(TLV320AIC3104)"), T("0x18")},
{ T("Chip ID GPIO(PCA9500)"),T("0x20")},
{ T("GPIO - power rail control(PCA9555DB)"),T("0x24")},
{ T("Digital Potentiometer(AD5252)"),T("0x2C")},
{ T("Audience chip(eSxxx)"),T("0x3E")},
{ T("Spartan 3A FPGA(XC3SD3400A)"),T("0x40")},.......
Now In a constructor of the viewmodel class, I can add the items inside obs.Coll as follows:
public ObservableCollection<ModelClass> _I2CDeviceList = new ObservableCollection<ModelClass>()
{
new ModelClass() {I2CDevName = "Other", I2CDeviceAddress= "0x00"},
new ModelClass() {I2CDevName = "TI Codec", I2CDeviceAddress = "0x18"}, .........
};
but its a tedious job to add 15 items and I end up having 15 items statements. Is their a way i can add the items using a single loop to avoid many statements?
So either you make a constructor to the ModelClass which makes it easier for you to create, and at the same time fill in the values.
This would reduce the code somewhat but there still will be some typing:
Or you can make a “factory”, a static function in the ModelClass that takes a whole list and returns a whole ObservableCollection
So you will have to change some in the list that you have, but if you change that to something like (maybe someone can come up with a better idea to use the list better, but:
And then add the static function to the ModelClass:
And then just run:
Tada…