我正在尝试使用WPF数据绑定(bind)功能来获取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控件为空白?

最佳答案

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

public ReadOnlyCollection<Category> FirstGeneration { get; set; }

关于c# - 数据绑定(bind)到XAML中的TreeView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12162034/

10-13 06:27