我是一位有用的助手,可以为您翻译文本。
我一直以来都在使用LINQ将对象绑定到ListView上遇到了一些问题。下面是我创建的一个测试用例:
C#:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
public class MySubClass {
public string subtitle;
}
public class MyClass
{
public string title;
public MySubClass subclass;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MySubClass sub = new MySubClass();
sub.subtitle = "This is the subtitle";
MyClass cls = new MyClass();
cls.title = "This is the title";
cls.subclass = sub;
ObservableCollection<MyClass> mylist = new ObservableCollection<MyClass>();
mylist.Add(cls);
mylist.Add(cls);
listView1.ItemsSource = (from c in mylist select new List<MyClass> {c}).ToList();
label1.Content = listView1.Items.Count.ToString();
}
}
}
XAML:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListView ItemsSource="{Binding}" Name="listView1" Height="200" Grid.Row="0">
<ListView.View>
<GridView>
<GridViewColumn Header="Title" Width="80" DisplayMemberBinding="{Binding Path=title}" />
<GridViewColumn Header="Subtitle" Width="80" DisplayMemberBinding="{Binding subclass.subtitle}" />
</GridView>
</ListView.View>
</ListView>
<Label Name="label1" Grid.Row="1" ></Label>
</Grid>
</Window>
当运行时,我期望此代码在列表视图中显示标题和副标题属性。但实际上没有显示,但是列表视图的Count()正确地显示了它有2个项目。我认为我绑定到了错误的属性...我应该在绑定中使用不同的语法吗?
谢谢, Ian