【问题标题】:Treeview not showing data树视图不显示数据
【发布时间】:2011-12-18 12:22:17
【问题描述】:

我一直在尝试重现这个例子:http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx

由于某种原因,我的树视图根本没有显示任何数据,我不知道为什么(我没有收到任何错误,也不知道如何体面地调试它)。这是我的代码:

MainWindow.XAML

<Window x:Class="Tryout.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Tryout.domain"
    Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<TreeView Name="treeViewFiles" HorizontalAlignment="Left" Margin="10,10,0,12" Width="200" ClipToBounds="True">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Directory}" ItemsSource="{Binding Children}">
            <Label Content="{Binding Path=Name}"/>
        </HierarchicalDataTemplate>
        <DataTemplate DataType ="{x:Type local:File}">
            <TextBlock Text="{Binding Path=Name}" />
        </DataTemplate>
    </TreeView.Resources>
</TreeView>

MainWindow.XAML.cs

namespace Tryout
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Directory rootDirectory = new Directory("Root");
            rootDirectory.Children.Add(new Directory("Subdirectory 1"));
            rootDirectory.Children.Add(new Directory("Subdirectory 2"));
            ((Directory)rootDirectory.Children[1]).Children.Add(new File("The only file"));

            treeViewFiles.ItemsSource = rootDirectory.Children;
        }
    }
}

文件.cs

namespace Tryout.domain
{
    public class File : INotifyPropertyChanged
    {
        public string Name;

        public File(String _name)
        {
            Name = _name;
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}

目录.cs

namespace Tryout.domain
{
    public class Directory : File
    {
        public List<File> Children = new List<File>();

        public Directory(String _name) : base(_name) { }
    }
}

【问题讨论】:

    标签: c# wpf mvvm treeview


    【解决方案1】:

    您的FileDirectory 类通过字段而不是属性公开它们的数据,并且您不能绑定到字段。将公共字段 NameChildren 更改为属性,您的代码将起作用。

    【讨论】:

    • 是的,这解决了我的问题。不知道字段和属性之间实际上存在差异。认为我应该阅读更多关于 C# 的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多