2
我正在嘗試使用WPF數據綁定功能來獲取TreeView
以顯示對象(類別)的分層樹。將數據綁定到XAML中的TreeView
我大致遵循this tutorial by Josh Smith,但無效:我的TreeView
中沒有出現任何項目。
這是我非常簡單的應用程序的完整代碼:
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = CategoriesTreeViewModel.CreateDefault;
}
}
}
視圖模型對象和樣本數據:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace WpfApplication1
{
public class Category
{
public Category()
{
Children = new ObservableCollection<Category>();
}
public ObservableCollection<Category> Children
{
get;
set;
}
public string Name { get; set; }
}
public class CategoriesTreeViewModel
{
public ReadOnlyCollection<Category> FirstGeneration;
private static IEnumerable<Category> SomeCategories
{
get
{
var A = new Category() { Name = "A" };
var B = new Category() { Name = "B" };
var A1 = new Category() { Name = "A1" };
var A2 = new Category() { Name = "A2" };
var B1 = new Category() { Name = "B1" };
var B2 = new Category() { Name = "B2" };
A.Children.Add(A1);
A.Children.Add(A2);
B.Children.Add(B1);
B.Children.Add(B2);
yield return A;
yield return B;
}
}
public static CategoriesTreeViewModel CreateDefault
{
get
{
var result = new CategoriesTreeViewModel()
{
FirstGeneration = new ReadOnlyCollection<Category>(SomeCategories.ToList())
};
return result;
}
}
}
}
和XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView ItemsSource="{Binding FirstGeneration}" Name="treeView1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
爲什麼TreeView
控制空白?
在輸出窗口中是否有任何綁定錯誤?你有沒有嘗試綁定到你的DataContext上的其他任何東西來驗證綁定是否正常工作? – Thelonias
@Ryan:'System.Windows.Data錯誤:40:BindingExpression路徑錯誤:'對象'''CategoriesTreeViewModel'(HashCode = 62819840)'找不到'FirstGeneration'屬性。 BindingExpression:路徑=第一代; ' –