2

我正在尝试使用 WPF 数据绑定功能来TreeView显示对象(类别)的层次结构树。

我大致遵循了 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控件是空白的?

4

1 回答 1

5

您无法访问您的 FirstGeneration 财产。没有“get”访问器的属性被认为是只写的。

public ReadOnlyCollection<Category> FirstGeneration { get; set; }
于 2012-08-28T15:09:23.043 回答