我想把一個ObservableCollection系結到ListView上。
class TestClass
{
public string attribute1 { get; set; }
public string attributes2 { get; set; }
public string attributes { get; set; }
}
static public ObservableCollection<TestClass> GetTestClassCollection()
{
SpecialObjects[] specialobject = Class.GetSpecialObjects()。
ObservableCollection<TestClass> specialTestObjects = new ObservableCollection<TestClass>()。
foreach (SpecialObject special in specialobject)
{
specialTestObjects.Add(new TestClass() { attribute1 = special.attribute1, attribute2 = special.attribute2, attribute3 = special.attribute3 }) 。
}
return specialTestObjects。
}
我的MainWindow.xaml
<!--資料模板-->
<Window.Resources>/span>
<ListView x:Key="ListViewTemplate"/span>>
<ListView.ItemTemplate>/span>
<DataTemplate>/span>
<StackPanel>/span>
<TextBlock Text="{Binding attribute1}"/gt;
<TextBlock Text="{系結屬性2}"/span> />
<TextBlock Text="{系結屬性3}"/span> />
</StackPanel>
</DataTemplate>/span>
</ListView.ItemTemplate>
</ListView>/span>
</Window.Resources>
......這里是創建ListView的方法內容(當你點擊一個按鈕時就會被呼叫)
ListView listView = new ListView();
listView.ItemsSource = TestClass.GetTestClassCollection()。
listView.ItemTemplate = (DataTemplate)this.FindResource("ListViewTemplate") 。
mainGrid.Children.Add(listView)。
一旦我點擊按鈕,應用程式就會崩潰。
我搜索了一些ListView模板的參考資料,但它們似乎都和我的很相似。但是很明顯,有些地方不匹配。
當我試圖分配ItemTemplate的時候,應用程式崩潰了。
謝謝! uj5u.com熱心網友回復: 錯誤資訊相當清楚。 要求該資源是一個DataTemplate,但實際上它是一個ListView。 資源宣告應該是這樣的: 資源宣告應該是這樣的:
標籤:無法將'System.Windows.Controls.ListView'型別的物件轉換為'System.Windows.DataTemplate'型別。
(DataTemplate)this.FindResource("ListViewTemplate")
<Window.Resources>
<DataTemplate x:Key="ListViewTemplate"/span>>
<StackPanel>
<TextBlock Text="{Binding attribute1}" />
<TextBlock Text="{Binding attribute2}" />
<TextBlock Text="{Binding attribute3}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
