【发布时间】:2016-02-24 13:23:41
【问题描述】:
我是 WPF 中数据绑定的新手,并试图理解概念。我要做的是将可观察的集合数据绑定到列表视图。为此,我创建了两个类:
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;
}
}
在主窗口中,我实例化了我的员工列表:
public MainWindow()
{
InitializeComponent();
Employee_list l = new Employee_list() { list = { new Employee("Alex", "Z"), new Employee ("Alex", "K")}};
}
现在我需要将此列表的内容绑定到 ListView:
我知道我可以通过三种方式做到这一点 - 1
RelativeSource:相对源是绑定上的属性之一,它可以指向相对源标记扩展,该扩展指示可以在层次结构中找到源的位置。简单来说就是元素层次结构中的相对路径。
ElementName:另一种指定源的方法是使用 ElementName,其中当前 UI 中存在可用作源对象的另一个元素。这里源对象必须是可视化树的一部分。
Source:另一种方法是在绑定上使用 Source 属性。此源属性必须指向某个对象引用,并且将对象引用向下传递到 Source 属性的唯一更好的方法是使用指向资源集合中某个对象的静态资源。
我尝试通过 Source 和 Resources 来实现,但在这种情况下,我可以指定类本身,而不是指定包含内容的特定集合:
<Window.Resources>
<localc:Employee_list x:Key="EmployeeList" />
</Window.Resources>
您能否帮助我了解我该怎么做以及正确的方法是什么?
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>
【问题讨论】:
标签: c# wpf xaml listview data-binding