I'm new to data binding in WPF and trying to understand concepts. What I'm trying to do is bind observable collection data to list view. For that purposes I have created two classes:
public class Employee_list
{
public ObservableCollection<Employee> list = new ObservableCollection <Employee>();
public Employee_list()
{
}
}
public class Employee
{
public string name { get; set; }
public string surname { get; set;}
public Employee(string name, string surname)
{
this.name = name;
this.surname = surname;
}
}
In the main window I've instantiated my list of Employees:
public MainWindow()
{
InitializeComponent();
Employee_list l = new Employee_list() { list = { new Employee("Alex", "Z"), new Employee ("Alex", "K")}};
}
Now I need to bind content of this list to ListView:
I understand that I can do it in three ways as per - 1
RelativeSource: Relative source is one of the properties on a binding that can point to relative source markup extension that tells where the source can be found in hierarchy. In simple words, it is the relative path in the element hierarchy.
ElementName: Another way of specifying a source is by using an ElementName in which another element is present in the current UI that can be used as a source object. Here the source object must be part of the visual tree.
Source: Another way is by using the Source property on a binding. This source property must point to some object reference and the only better way to get an object reference down into the Source property is to use a static resource that points to some object in a resource collection.
I'm try to do it via Source and Resources, but in that case I am able to specify class itself and not a specific collection with content:
<Window.Resources>
<localc:Employee_list x:Key="EmployeeList" />
</Window.Resources>
Could you please help me to understand how I can do it and what is the proper way to do it?
XAML:
<Window x:Name="mw"
x:Class="binding_testing.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:localc="clr-namespace:binding_testing"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<localc:Employee_list x:Key="EmployeeList" />
</Window.Resources>
<Grid>
<ListView Name="myListBox" HorizontalAlignment="Left" Height="89" Margin="75,77,0,0" VerticalAlignment="Top" Width="393"
ItemsSource="{Binding Source={StaticResource EmployeeList}}" >
<ListView.View>
<GridView >
<GridViewColumn Header="Surname" Width="Auto" DisplayMemberBinding="{Binding surname}" />
<GridViewColumn Header="Name" Width="Auto" DisplayMemberBinding="{Binding name}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>