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個項目。我認爲我綁定了錯誤的屬性....我應該在綁定中使用不同的語法嗎?
感謝, 伊恩
嗨馬克 已經企圖 - 悲傷沒有任何區別。另外,LINQ查詢在真實應用程序中更加複雜,所以我有興趣查看保留LINQ查詢的解決方案。 謝謝! – 2009-02-22 19:51:33