【问题标题】:Binding to a treeview programatically not working in UWP以编程方式绑定到树视图在 UWP 中不起作用
【发布时间】:2019-12-14 18:23:59
【问题描述】:

我正在关注this 文章,尝试以编程方式将数据绑定到树视图(我在 1903 年)。

在一个全新的 UWP 应用中,我有以下代码:

public MainPage()
{
    this.InitializeComponent();

    var items = new List<Item>();
    var rootItem = new Item();
    rootItem.Name = "Root Item";
    rootItem.Children.Add(new Item() { Name = "test child 1" });
    items.Add(rootItem);

    var treeView = new TreeView();
    treeView.ItemsSource = items;
    stackPanel.Children.Add(treeView);
}

Item 看起来像这样:

public class Item
{
    public string Name { get; set; }
    public ObservableCollection<Item> Children { get; set; } = new ObservableCollection<Item>();

    public override string ToString()
    {
        return Name;
    }
}

这似乎是上述文章中概述的确切结构。但是,当我运行应用程序时,我得到了这个:

我的猜测是我需要做,或者设置一些东西来告诉这个树视图,或者它有孩子的集合 - 但我看不出那可能是什么。

【问题讨论】:

    标签: c# uwp treeview


    【解决方案1】:

    您应该按照docs 中的说明创建一个ItemTemplate

    您可以使用XamlReader 类以编程方式执行此操作。像这样的:

    const string Xaml = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><TreeViewItem ItemsSource=\"{Binding Children}\" Content=\"{Binding Name}\"/></DataTemplate>";
    treeView.ItemTemplate = XamlReader.Load(Xaml) as DataTemplate;
    

    【讨论】:

    • 我曾尝试过这种事情,但无法让它发挥作用。我已经尝试过您的代码以及四种变体中的三种,但它们似乎都不是有效的模板。
    • 对不起 - 我的错 - 它工作正常。您的答案中有一个类型,根注释的开头有一个 />,但是我不允许编辑它
    • @CuriousDev:已编辑。
    【解决方案2】:

    如果您使用 C# 构建 TreeView,我建议使用遍历添加 TreeViewNode。

    由于缺少指令,TreeView 不会自动处理 Item 的 Children。在您提供的文档中,TreeView 有一个 DataTemplate 指令,因此孩子们可以渲染。

    您可以像这样更改代码:

    public MainPage()
    {
        this.InitializeComponent();
        var items = new List<Item>();
        var rootItem = new Item();
        rootItem.Name = "Root Item";
        rootItem.Children.Add(new Item() { Name = "test child 1" });
        items.Add(rootItem);
        var treeView = new TreeView();
    
        foreach (var root in items)
        {
            var rootNode = new TreeViewNode() { Content = root.Name };
            if (root.Children.Count > 0)
            {
                foreach (var child in root.Children)
                {
                    rootNode.Children.Add(new TreeViewNode() { Content = child.Name });
                }
            }
            treeView.RootNodes.Add(rootNode);
        }
        stackPanel.Children.Add(treeView);
    }
    

    最好的问候。

    【讨论】:

    • 我实际上只是从这种方法中改变了它。主要原因是我需要针对节点存储比单个字符串更多的信息。
    • 您好,如果选择这种方式创建TreeView,后续对节点的修改需要通过查找节点来完成。如果要使用数据集渲染 TreeView,最好使用DataTemplate 绑定数据。
    • 这是@mm8 的建议,但我似乎无法以编程方式输入模板。
    猜你喜欢
    • 1970-01-01
    • 2020-11-18
    • 2017-04-04
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    相关资源
    最近更新 更多