LINQ to Objects - 绑定到ListView

时间:2009-02-22 19:40:13

标签: c# linq data-binding xaml

我一直遇到使用LINQ将ListView绑定到Object的问题。最好用我创建的测试用例解释:

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>

运行时,我希望此代码在listview中显示标题和副标题属性。它没有,但listview Count()正确显示它有2个项目。我想我绑定了错误的属性....我应该在绑定中使用不同的语法吗?

谢谢, 伊恩

1 个答案:

答案 0 :(得分:5)

(的更新

重新使用xaml,看起来你错过了一行中的“Path =”:

{Binding subclass.subtitle}

重新对象;它可能需要属性;尝试:

    public class MySubClass {
        public string subtitle {get;set;}
    }
    public class MyClass
    {
        public string title {get;set;}
        public MySubClass subclass {get;set;}
    }

该行:

(from c in mylist select new List<MyClass> {c}).ToList();

创建一个列表列表,每个列表都有一个元素(外部列表中有两个项目)。只需将mylist设置为源:

listView1.ItemsSource = mylist;

如果你想在LINQ查询中做一个“有趣”的投影,那么它看起来更像是:

(from c in mylist select new { Foo = c.SomeProp,
    Bar = c.SomeOtherProp + 12 }).ToList();

这是一个单独的列表,只是与原始列表中的不同项目。