Binding collection of custom classes to TreeView

后端 未结 1 1585
遇见更好的自我
遇见更好的自我 2021-02-10 20:21

I\'m trying to determine the best way to accomplish binding a Collection of a custom class to a TreeView.

I currently have two custom classes, one held in a Collection,

1条回答
  •  被撕碎了的回忆
    2021-02-10 21:11

    When dealing with a TreeView, I usually end up generating a wrapper class that inherits from TreeNode and which holds the actual object that I'm displaying as the node. That way I can bind to the TreeView, get the heirarchy I need, and my business classes don't actually have to subclass a UI component. It works nicely when handling the TreeView events as well, because you can just inspect the node for its type and different typed nodes can be handled differently - display a different UI or whatever.

    private class FooNode : TreeNode
    {
        public FooNode(Foo foo)
        {
            this.Text = foo.ToString(); //Or FriendlyName
            this.Foo = foo;
            this.Foo.Bars.ForEach(x => this.Nodes.Add(new BarNode(x)));
        }
    
        public Foo Foo
        {
            get;
            private set;
        }
    }
    
    private class BarNode : TreeNode
    {
        public BarNode(Bar bar)
        {
            this.Text = bar.ToString(); //Or FriendlyName
            this.Bar = bar;
        }
    
        public Bar Bar
        {
            get;
            private set;
        }
    }
    

    This example may be exactly what you mean by your second option. In that case, I vote for the second option!

    0 讨论(0)
提交回复
热议问题