I have class in a class. In view model i have system status property, in another class i am writing pc names by hand...for 150 pc's i create property for status PCs. What is the best way to make this clearly?
public class Computers
{
public Computers()
{
computer1 = new SeriesViewModel();
computer2 = new SeriesViewModel();
computer3 = new SeriesViewModel();
//over 150 computer
}
SeriesViewModel computer1 { get; set; }
SeriesViewModel computer2 { get; set; }
SeriesViewModel computer3 { get; set; }
//over 150 computer
}
public class ComputerInfos: INotifyPropertyChanged
{
public ComputerInfos()
{
}
private string compname;
private string serialno;
public string ComputerName
{
get { return compname; }
set
{
compname= value;
OnPropertyChange(this,ComputerName );
}
}
public string SerialNumber
{
get { return serialno; }
set
{
serialno= value;
OnPropertyChange(this,SerialNumber);
}
}
}
In main window, I write over computers like below, but it takes too much effort and times. How can I make it easier?
public partial class MainWindow : Window
{
private Computers computer;
public MainWindow()
{
InitializeComponent();
computer = new Computers ();
DataContext = computer;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
computer.computer1.ComputerName = "Computer 1";
computer.computer1.SerialNumber = "1N-C1";
computer.computer2.ComputerName = "Computer 2";
computer.computer2.SerialNumber = "1N-C2";
computer.computer3.ComputerName = "Computer 3";
computer.computer3.SerialNumber = "1N-C3";
// for each computers writing like this is bad
}
}
CodePudding user response:
In this cases, we use ObservableCollection<T>
class
You can check from here
You can use ObservableCollection
like this;
public class Computers
{
public Computers()
{
ComputerInfo = new ObservableCollection<ComputerInfos>();
for(int i = 0; i<150; i )
{
ComputerInfo.Add(new ComputerInfos());
}
}
public ObservableCollection<ComputerInfos> ComputerInfo { get; }
}
For 150 Computers, you can use For Loop
to each ComputerInfos
class to ComputerInfo
collection.
Then, you get or set each computer informations in your Main Windows get easier.
public partial class MainWindow : Window
{
private Computers computer;
public MainWindow()
{
InitializeComponent();
computer = new Computers ();
DataContext = computer;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 1; i <=150; i )
{
computer.ComputerInfo[i-1].ComputerName = "Computer " i.Tostring();
computer.ComputerInfo[i-1].SerialNumber = "1N-C" i.ToString();
}
}
}