【发布时间】:2012-08-28 14:55:26
【问题描述】:
我正在尝试使用 WPF 数据绑定功能来获取 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;
}
}
}
ViewModel 对象和示例数据:
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 上的任何其他内容以验证绑定是否有效?
-
@Ryan:
System.Windows.Data Error: 40 : BindingExpression path error: 'FirstGeneration' property not found on 'object' ''CategoriesTreeViewModel' (HashCode=62819840)'. BindingExpression:Path=FirstGeneration;
标签: c# wpf xaml data-binding mvvm