cerberus23 cerberus23 - 1 year ago 60
C# Question

binding a listview to a property of an object in a list of objects

I'm a new to C# and I'm practicing my knowledge through WPF.. I'm trying to create an "EmployeeDatabase"

public EmployeeDB()
_employeeList.Add(new EmployeeApp1.Employee() { Name = "Hecbert Doval", Email = "haloha@gmail.com", Salary = 14000 });
_employeeList.Add(new EmployeeApp1.Employee() { Name = "Harry Pottah", Email = "haloha@gmail.com", Salary = 653000 });
_employeeList.Add(new EmployeeApp1.Employee() { Name = "Amino Vikola", Email = "haloha@gmail.com", Salary = 230 });
_employeeList.Add(new EmployeeApp1.Employee() { Name = "Mila Spino", Email = "haloha@gmail.com", Salary = 30000 });
_employeeList.Add(new EmployeeApp1.Employee() { Name = "Tila Tequila", Email = "haloha@gmail.com", Salary = 90700 });
_employeeList.Add(new EmployeeApp1.Employee() { Name = "TheRock Johnson", Email = "haloha@gmail.com", Salary = 14500 });
private List<Employee> _employeeList;

that uses a List of "Employee" objects and each of these Employee objects has "Name, Salary, email" as properties.

public class Employee
public string Name { get; set; }
public string Email { get; set; }
public int Salary { get; set; }

Next I created 3 listviews, arranged them to side by side, and each one should receive "Name" "Email" and "Salary" alone.

<ListView Name="lvName" Margin="20" Grid.Column="0" />
<ListView Name="lvEmail" Margin="20" Grid.Column="1" />
<ListView Name="lvSalary" Margin="20" Grid.Column="2" />

My question is how can I bind each ListView to the Name / Email/ Salary ? if it's possible.. if not any alternatives to achieve the same result ?
Thanks in advance!

Answer Source

Out of curiosity, why would you want three adjacent listviews, each displaying only one property?

By the way, are you implementing INotifyPropertyChanged? You should be.

Anyway, this is easy. First, expose _employeeList:

private ObservableCollection<Employee> _employeeList
    = new ObservableCollection<Employee>();

public ObservableCollection<Employee> EmployeeList { get { return _employeeList; } }

Then, bind:

    ItemsSource="{Binding EmployeeList}" 
    Margin="20" Grid.Column="0" 

    ItemsSource="{Binding EmployeeList}" 
    Margin="20" Grid.Column="1" 

    ItemsSource="{Binding EmployeeList}" 
    Margin="20" Grid.Column="2" 

If you'd rather do everything in codebehind, that's trivial to figure out for yourself given what I've shown you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download