2009-02-22 64 views
4

我一直在使用LINQ將ListView綁定到對象的問題。它是最好的我已經創建了一個測試用例解釋說:LINQ to Objects - 綁定到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> 

在運行的時候,我會想到這個代碼顯示在標題和副標題屬性列表視圖。它不,但listview Count()正確顯示它有2個項目。我認爲我綁定了錯誤的屬性....我應該在綁定中使用不同的語法嗎?

感謝, 伊恩

回答

5

更新

重新XAML中,它看起來就像你在該行缺少 「PATH =」:

{Binding subclass.subtitle} 

的Re對象;它可能需要屬性;嘗試:

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(); 

這是話單清單,只是將不同的項目放在原始列表中。

+0

嗨馬克 已經企圖 - 悲傷沒有任何區別。另外,LINQ查詢在真實應用程序中更加複雜,所以我有興趣查看保留LINQ查詢的解決方案。 謝謝! – 2009-02-22 19:51:33