C# WPF Listview 绑定到 ItemSource?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2221621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Listview binding to ItemSource?
提问by Tony The Lion
I have the following listview, but it doesn't show the actual records, but only the namespace of the object. I wondered if I need to create the columns in XAML for it to show the records and then bind it to some properties of an object or what is wrong with this?
我有以下列表视图,但它不显示实际记录,而只显示对象的命名空间。我想知道是否需要在 XAML 中创建列以显示记录,然后将其绑定到对象的某些属性,或者这有什么问题?
<ListView
Name="ListCustomers"
ItemsSource="{Binding Path=ListOfCustomers}"
SelectedItem="{Binding Path=SelectedCustomer}"
SelectionMode="Single"
IsSynchronizedWithCurrentItem="True"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
MinHeight="100"
></ListView>
ListOfCustomers
is an ObservableCollection<Customer>
type. The actual customers do get loaded into the ObservableCollection, but they are not displayed. What is missing?
ListOfCustomers
是一种ObservableCollection<Customer>
类型。实际客户确实会加载到 ObservableCollection 中,但不会显示它们。有什么不见了?
采纳答案by ChrisF
You need to select the columns to display as well:
您还需要选择要显示的列:
<ListView ItemsSource="{Binding ListOfCustomers}"
SelectedItem="{Binding Path=SelectedCustomer}"
....>
<ListView.View>
<GridView>
<GridViewColumn Width="140" Header="First Name"
DisplayMemberBinding="{Binding FirstName}" />
<GridViewColumn Width="140" Header="Last Name"
DisplayMemberBinding="{Binding LastName}" />
<GridViewColumn Width="140" Header="Email Address"
DisplayMemberBinding="{Binding Email}" />
....
</GridView>
</ListView.View>
</ListView>
回答by Gishu
Is it because you have not set the DataContext
property of the ListView with the instance that exposes the ListOfCustomers
property (which returns the list of items to be displayed) ?
是不是因为您没有DataContext
使用公开ListOfCustomers
属性的实例(返回要显示的项目列表)设置ListView 的属性?
回答by miensol
You could also try
你也可以试试
<ListView
.
.
ItemTemplate="{StaticResource CustomerDataTemplate}"
.
.
/>
where CustomerDataTemplate is a DataTemplate for Customer class...
其中 CustomerDataTemplate 是 Customer 类的 DataTemplate...