Wpf tree

Wpf tree DEFAULT

Using the WPF Tree View with Multiple Levels

There are many examples of using the Windows Presentation Foundataion (WPF) Tree View that you can find on the Web, however, most of them only show you how to go to two levels. What if you have more than two levels? This is where it’s vital to understand exactly how the Hierarchical Data Templates work. In this article, I’m going to break down how these templates work, so you can really understand what’s going on underneath the hood.

A Hard-Coded WPF Tree View

To start, let’s look at the typical two-level WPF Tree View that has been hard-coded with the values shown in the following code snippet.

Figure 1 shows you how this Tree View looks when you run the WPF application.

Create Hierarchical Classes to Mimic Your Tree View

You don’t want to use hard-coded XAML in your WPF application. You want to retrieve data from a database table or an XML file and build the Tree View dynamically. How and from where you retrieve the data is not important for this article. What’s important is how you structure the classes into which your data will be placed. Just as a Tree View is a hierarchical structure, create a set of classes that is also a hierarchy.

Figure 2 shows the three classes that will be necessary for expressing a hierarchy of Employee Type objects of which each Employee Type object can hold one or more Employee objects.

The first class you build is the Employee class. This class has a single property called Name. A constructor is created to accept a “name” argument that you can use to set the Name property when you create an Employee object.

The EmployeeType class contains two properties. First is a string property, called Description, which holds the name of the employee type, such as “Supervisor” or “Project Manager.” The second property, Employees, is a generic collection property to hold a list of Employee objects that are associated with this particular employee type.

The last class you create is collection class called EmployeeTypes created using the generic List class. This is a collection of EmployeeType objects. In the constructor of the EmployeeTypes collection class, you build the collection of EmployeeType objects and fill each one with Employee objects, as shown in Listing 1. For purposes of this article, I’m using hard-coded data. Feel free to load this collection with the data of your choice.

If you create an instance of the EmployeeTypes class as shown in the following code snippet, you will create the hierarchy of employee types and employees shown in Figure 3.

If you compare Figure 1 and Figure 3, you can see that the two structures are very similar. At the top, you have the employee types (Manager and Project Managers), and the next level under each employee type is a collection of employee objects (Tim, John, David). Matching your class hierarchy to the Tree View display is your first step in ensuring that you can display your data in a Tree View format.

Create Your Data and Data Templates using XAML

When using XAML, you don’t need to create an instance of the EmployeeTypes class in C# or Visual Basic code. Instead, you use XAML to create the instance of the EmployeeTypes class as shown in line 12 of Figure 4. Provide your instance of EmployeeTypes with a name using the “x:Key” attribute, in this example, theData. Notice in line 28 of Figure 4 that the ItemsSource of the Tree View control is using the static resource with the key of theData as the source of data for the Tree View.

With the ItemsSource property of the Tree View control set to the collection of EmployeeType objects, you are now ready to start building the hierarchy of XAML DataTemplate objects. What’s important here is that the last level displayed in your Tree View is expressed in a <DataTemplate> listed first in your Resources section, as shown in lines 14-16 of Figure 4. Notice that the TextBlock control within the <DataTemplate> is bound to the Name property of your Employee class. The employee name is indeed what shows up in the last level of the Tree View shown in Figure 1.

As this is just a two-level Tree View, you only need a single <HierarchicalDataTemplate> resource listed after the <DataTemplate> resource. Set the ItemTemplate property in your Hierarchical Data Template to the key name of the Data Template. Set the ItemsSource property to the collection of objects that contain the path of the data expressed in the Data Template. In this case, the ItemsSource uses the Employees property as the collection of Employee objects. Each Employee object has a Name property that’s used in the Data Template to display the name of the employee in the Tree View.

In the <HierarchicalDataTemplate> resource, you use a TextBlock to display the appropriate EmployeeType property in the first level of the Tree View. The TextBlock control in line 20 of Figure 4 uses the Description property of the EmployeeType class.

The Tree View control has its ItemTemplate property set to the key of the last <HierarchicalDataTemplate> resource in your Resources section. The order of the XAML you create for a Tree View is important. The lowest level you wish to display within your Tree View control needs to be listed first in your Resources section. The reason for this should be fairly obvious: Each resource as you work down through the Resources section needs to reference an “x:Key” of another XAML element. XAML can only reference keys that have been previously defined.

Three Levels in a Tree View

Now let’s expand upon the two-level Tree View and use three levels in the Tree View. The Tree View shown in Figure 5 again uses the EmployeeTypes at the top of the tree, followed by a small set of employees that themselves manage employees. To make this Tree View display, modify the Employee class to contain a collection of Employee objects (named ManagedEmployees) as shown in the following code snippet.

Next, you need to modify the constructor of the EmployeeTypes class to create a list of managed employees within each Employee object. Listing 2 shows the new code where, after creating an Employee object, you add another employee to the ManagedEmployees property.

Now that you have your three-level structure built into your classes, you are ready to hook up this three-level structure to your Tree View. As you might expect, you are going to add another <HierachicalDataTemplate> in between the old <HierachicalDataTemplate> and the <DataTemplate> shown in Figure 4. Of course, one of the x:Key attributes will have to change in order to accommodate this new template.

Figure 6 shows the complete XAML needed to hook up your three-level Tree View. You can see in the XAML that there are now two Hierarchical Data Templates and one Data Template. Again, you list the Data Template first, because that’s the lowest level in your Tree View. The next Hierarchical Data Template listed is the next level up from the lowest level, and finally you have a Hierarchical Data Template for the first level in your tree. As mentioned before, you always work your way from the bottom up when creating your Tree View hierarchy. XAML is processed from the top down, so any attempt to reference an XAML x:Key that’s below where you’re referencing it from results in a runtime error.

Each Hierarchical Data Template uses the x:Key name of the previous template as its ItemTemplate. The ItemsSource of each Hierarchical Data Template is used to feed the data to the previous template. This is probably the most confusing part about working with the Tree View control. You expect the content of the current Hierarchical Data Template to use the properties set in the ItemsSource property of that template. But you need to look to the template lower down in the XAML to see the source of the data, as shown in Figure 7.


Understanding how to put together your hierarchy in a Tree View is simple once you understand that you need to work from the bottom up. Start with the bottom node in your Tree View and determine what that will look like and where the data will come from. Then build the next Hierarchical Data Template to feed the data to the previous template you created. You keep doing this for each level in your Tree View until you get to the last level. The data for that last Hierarchical Data Template comes from the ItemsSource in the Tree View itself. Structure your data classes to mimic the hierarchical structure of your Tree View, and displaying a Tree View becomes quite simple.

NOTE: You can download the sample code for this article by visiting my website at http://www.pdsa.com/downloads. Select PDSA Articles, then select Code Magazine: WPF TreeView with Multiple Levels from the drop-down list.

CODE Training offers training on a variety of topics, including WPF, HTLM 5, Javascript, and even .NET from a Visual Fro Pro point of view. Corporate Training Accounts provide organizations that have sophisticated training needs with a way to train their staff in order to keep up with new and emerging technologies. With a Corporate Training Account, “Training Vouchers” provide companies with access to CODE Training courses at significantly reduced rates! Training Vouchers can be used flexibly and applied toward any of our publicly scheduled classes.

$250 per seat (seats are transferable and never expire)

Minimum $5,000 investment

Select classes for developers individually based upon areas each developer needs assistance, or use vouchers to bring your entire staff to the same class.

Visit www.codemag.com/training/corporate email Iain at [email protected] for more information.

Have additional technical questions?

Get help from the experts at CODE Magazine - sign up for our free hour of consulting!

Contact CODE Consulting at [email protected]

Sours: https://www.codemag.com/article/1401031/Using-the-WPF-Tree-View-with-Multiple-Levels

TreeView Overview

  • 3 minutes to read

The TreeView control provides a way to display information in a hierarchical structure by using collapsible nodes. This topic introduces the TreeView and TreeViewItem controls, and provides simple examples of their use.

What Is a TreeView?

TreeView is an ItemsControl that nests the items by using TreeViewItem controls. The following example creates a TreeView.

Creating a TreeView

The TreeView control contains a hierarchy of TreeViewItem controls. A TreeViewItem control is a HeaderedItemsControl that has a Header and an Items collection.

If you are defining a TreeView by using Extensible Application Markup Language (XAML), you can explicitly define the Header content of a TreeViewItem control and the items that make up its collection. The previous illustration demonstrates this method.

You can also specify an ItemsSource as a data source and then specify a HeaderTemplate and ItemTemplate to define the TreeViewItem content.

To define the layout of a TreeViewItem control, you can also use HierarchicalDataTemplate objects. For more information and an example, see Use SelectedValue, SelectedValuePath, and SelectedItem.

If an item is not a TreeViewItem control, it is automatically enclosed by a TreeViewItem control when the TreeView control is displayed.

Expanding and Collapsing a TreeViewItem

If the user expands a TreeViewItem, the IsExpanded property is set to . You can also expand or collapse a TreeViewItem without any direct user action by setting the IsExpanded property to (expand) or (collapse). When this property changes, an Expanded or Collapsed event occurs.

When the BringIntoView method is called on a TreeViewItem control, the TreeViewItem and its parent TreeViewItem controls expand. If a TreeViewItem is not visible or partially visible, the TreeView scrolls to make it visible.

TreeViewItem Selection

When a user clicks a TreeViewItem control to select it, the Selected event occurs, and its IsSelected property is set to . The TreeViewItem also becomes the SelectedItem of the TreeView control. Conversely, when the selection changes from a TreeViewItem control, its Unselected event occurs and its IsSelected property is set to .

The SelectedItem property on the TreeView control is a read-only property; hence, you cannot explicitly set it. The SelectedItem property is set if the user clicks on a TreeViewItem control or when the IsSelected property is set to on the TreeViewItem control.

Use the SelectedValuePath property to specify a SelectedValue of a SelectedItem. For more information, see Use SelectedValue, SelectedValuePath, and SelectedItem.

You can register an event handler on the SelectedItemChanged event in order to determine when a selected TreeViewItem changes. The RoutedPropertyChangedEventArgs<T> that is provided to the event handler specifies the OldValue, which is the previous selection, and the NewValue, which is the current selection. Either value can be if the application or user has not made a previous or current selection.

TreeView Style

The default style for a TreeView control places it inside a StackPanel object that contains a ScrollViewer control. When you set the Width and Height properties for a TreeView, these values are used to size the StackPanel object that displays the TreeView. If the content to display is larger than the display area, a ScrollViewer automatically displays so that the user can scroll through the TreeView content.

To customize the appearance of a TreeViewItem control, set the Style property to a custom Style.

The following example shows how to set the Foreground and FontSize property values for a TreeViewItem control by using a Style.

Adding Images and Other Content to TreeView Items

You can include more than one object in the Header content of a TreeViewItem. To include multiple objects in Header content, enclose the objects inside a layout control, such as a Panel or StackPanel.

The following example shows how to define the Header of a TreeViewItem as a CheckBox and TextBlock that are both enclosed in a DockPanel control.

The following example shows how to define a DataTemplate that contains an Image and a TextBlock that are enclosed in a DockPanel control. You can use a DataTemplate to set the HeaderTemplate or ItemTemplate for a TreeViewItem.

See also

Sours: https://docs.microsoft.com/en-us/dotnet/desktop/wpf/controls/treeview-overview
  1. Vsco star emoji
  2. Logo color code
  3. 150 inch sofa
  4. Used audi tulsa
  5. Paper lightbox

The WPF Tree List (TreeListControl) is a data-aware control designed to display and edit hierarchical data. The TreeListControl allows users to manage data (sort, filter, and so on).


The Tree List is available as a stand-alone control or as one of Data Grid Views.

Get Started

Bind to Data

To display data within the TreeListControl, bind it to a data source.

Display Hierarchical Data

The TreeListControl can display data in a tree from a self-referential (flat) or hierarchical data structure.

Edit Data

The TreeListControl allows you to:

In-place Editing

In-place Editing

New Item Row

New Item Row

Sort Data

The TreeListControl allows you to Sort Data against one or multiple columns.

Filter and Search Data

The TreeListControl supports the following ways to filter and search data:

Automatic Filter Row & Filter Panel

Automatic Filter Row & Filter Panel

Column Drop-Down Filter

Column Drop-Down Filter

Search Panel

Search Panel

Display Summaries

The TreeListControl allows you to display Data Summaries for individual columns or children of each node. The control ships with a number of built-in functions, such as Sum, Maximum Value, Record Count, and others. You can also implement a custom aggregation function.

Select Data

The TreeListControl allows you to select nodes, cells, or their ranges.


The TreeListControl supports native drag-and-drop that allows users to:

Conditional Formatting

The TreeListControl supports Conditional Formatting. You can highlight critical information, identify trends and exceptions, and compare data.

Customize Appearance

The TreeListControl allows you to change the data layout, appearance, and visual presentation of elements (for example, cells, nodes, summaries, etc.).

Print and Export

The TreeListControl allows you to print data and export it in various formats - PDF, RTF, XLS, etc.


Extended design-time support allow you to configure the TreeListControl.

TreeList Quick Actions

Useful Resources

See Also


Thanks for your feedback!
Any other suggestions? Tell us here.

Sours: https://docs.devexpress.com/WPF/9759/controls-and-libraries/tree-list

Trees in WPF

  • 11 minutes to read

In many technologies, elements and components are organized in a tree structure where developers directly manipulate the object nodes in the tree to affect the rendering or behavior of an application. Windows Presentation Foundation (WPF) also uses several tree structure metaphors to define relationships between program elements. For the most part WPF developers can create an application in code or define portions of the application in XAML while thinking conceptually about the object tree metaphor, but will be calling specific API or using specific markup to do so rather than some general object tree manipulation API such as you might use in XML DOM. WPF exposes two helper classes that provide a tree metaphor view, LogicalTreeHelper and VisualTreeHelper. The terms visual tree and logical tree are also used in the WPF documentation because these same trees are useful for understanding the behavior of certain key WPF features. This topic defines what the visual tree and logical tree represent, discusses how such trees relate to an overall object tree concept, and introduces LogicalTreeHelper and VisualTreeHelpers.

Trees in WPF

The most complete tree structure in WPF is the object tree. If you define an application page in XAML and then load the XAML, the tree structure is created based on the nesting relationships of the elements in the markup. If you define an application or a portion of the application in code, then the tree structure is created based on how you assign property values for properties that implement the content model for a given object. In Windows Presentation Foundation (WPF), there are two ways that the complete object tree is conceptualized and can be reported to its public API: as the logical tree and as the visual tree. The distinctions between logical tree and visual tree are not always necessarily important, but they can occasionally cause issues with certain WPF subsystems and affect choices you make in markup or code.

Even though you do not always manipulate either the logical tree or the visual tree directly, understanding the concepts of how the trees interact is useful for understanding WPF as a technology. Thinking of WPF as a tree metaphor of some kind is also crucial to understanding how property inheritance and event routing work in WPF.


Because the object tree is more of a concept than an actual API, another way to think of the concept is as an object graph. In practice, there are relationships between objects at run time where the tree metaphor will break down. Nevertheless, particularly with XAML-defined UI, the tree metaphor is relevant enough that most WPF documentation will use the term object tree when referencing this general concept.

The Logical Tree

In WPF, you add content to UI elements by setting properties of the objects that back those elements. For example, you add items to a ListBox control by manipulating its Items property. By doing this, you are placing items into the ItemCollection that is the Items property value. Similarly, to add objects to a DockPanel, you manipulate its Children property value. Here, you are adding objects to the UIElementCollection. For a code example, see How to: Add an Element Dynamically.

In Extensible Application Markup Language (XAML), when you place list items in a ListBox or controls or other UI elements in a DockPanel, you also use the Items and Children properties, either explicitly or implicitly, as in the following example.

If you were to process this XAML as XML under a document object model, and if you had included the tags commented out as implicit (which would have been legal), then the resulting XML DOM tree would have included elements for and the other implicit items. But XAML does not process that way when you read the markup and write to objects, the resulting object graph does not literally include . It does however have a ListBox property named that contains a ItemCollection, and that ItemCollection is initialized but empty when the ListBox XAML is processed. Then, each child object element that exists as content for the ListBox is added to the ItemCollection by parser calls to . This example of processing XAML into an object tree is so far seemingly an example where the created object tree is basically the logical tree.

However, the logical tree is not the entire object graph that exists for your application UI at run time, even with the XAML implicit syntax items factored out. The main reason for this is visuals and templates. For example, consider the Button. The logical tree reports the Button object and also its string . But there is more to this button in the run-time object tree. In particular, the button only appears on screen the way it does because a specific Button control template was applied. The visuals that come from an applied template (such as the template-defined Border of dark gray around the visual button) are not reported in the logical tree, even if you are looking at the logical tree during run time (such as handling an input event from the visible UI and then reading the logical tree). To find the template visuals, you would instead need to examine the visual tree.

For more information about how XAML syntax maps to the created object graph, and implicit syntax in XAML, see XAML Syntax In Detail or XAML in WPF.

The Purpose of the Logical Tree

The logical tree exists so that content models can readily iterate over their possible child objects, and so that content models can be extensible. Also, the logical tree provides a framework for certain notifications, such as when all objects in the logical tree are loaded. Basically, the logical tree is an approximation of a run time object graph at the framework level, which excludes visuals, but is adequate for many querying operations against your own run time application's composition.

In addition, both static and dynamic resource references are resolved by looking upwards through the logical tree for Resources collections on the initial requesting object, and then continuing up the logical tree and checking each FrameworkElement (or FrameworkContentElement) for another value that contains a ResourceDictionary, possibly containing that key. The logical tree is used for resource lookup when both the logical tree and the visual tree are present. For more information on resource dictionaries and lookup, see XAML Resources.

Composition of the Logical Tree

The logical tree is defined at the WPF framework-level, which means that the WPF base element that is most relevant for logical tree operations is either FrameworkElement or FrameworkContentElement. However, as you can see if you actually use the LogicalTreeHelper API, the logical tree sometimes contains nodes that are not either FrameworkElement or FrameworkContentElement. For instance, the logical tree reports the Text value of a TextBlock, which is a string.

Overriding the Logical Tree

Advanced control authors can override the logical tree by overriding several APIs that define how a general object or content model adds or removes objects within the logical tree. For an example of how to override the logical tree, see Override the Logical Tree.

Property Value Inheritance

Property value inheritance operates through a hybrid tree. The actual metadata that contains the Inherits property that enables property inheritance is the WPF framework-level FrameworkPropertyMetadata class. Therefore, both the parent that holds the original value and the child object that inherits that value must both be FrameworkElement or FrameworkContentElement, and they must both be part of some logical tree. However, for existing WPF properties that support property inheritance, property value inheritance is able to perpetuate through an intervening object that is not in the logical tree. Mainly this is relevant for having template elements use any inherited property values set either on the instance that is templated, or at still higher levels of page-level composition and therefore higher in the logical tree. In order for property value inheritance to work consistently across such a boundary, the inheriting property must be registered as an attached property, and you should follow this pattern if you intend to define a custom dependency property with property inheritance behavior. The exact tree used for property inheritance cannot be entirely anticipated by a helper class utility method, even at run time. For more information, see Property Value Inheritance.

The Visual Tree

In addition to the concept of the logical tree, there is also the concept of the visual tree in WPF. The visual tree describes the structure of visual objects, as represented by the Visual base class. When you write a template for a control, you are defining or redefining the visual tree that applies for that control. The visual tree is also of interest to developers who want lower-level control over drawing for performance and optimization reasons. One exposure of the visual tree as part of conventional WPF application programming is that event routes for a routed event mostly travel along the visual tree, not the logical tree. This subtlety of routed event behavior might not be immediately apparent unless you are a control author. Routing events through the visual tree enables controls that implement composition at the visual level to handle events or create event setters.

Trees, Content Elements, and Content Hosts

Content elements (classes that derive from ContentElement) are not part of the visual tree; they do not inherit from Visual and do not have a visual representation. In order to appear in a UI at all, a ContentElement must be hosted in a content host that is both a Visual and a logical tree participant. Usually such an object is a FrameworkElement. You can conceptualize that the content host is somewhat like a "browser" for the content and chooses how to display that content within the screen region that the host controls. When the content is hosted, the content can be made a participant in certain tree processes that are normally associated with the visual tree. Generally, the FrameworkElement host class includes implementation code that adds any hosted ContentElement to the event route through subnodes of the content logical tree, even though the hosted content is not part of the true visual tree. This is necessary so that a ContentElement can source a routed event that routes to any element other than itself.

Tree Traversal

The LogicalTreeHelper class provides the GetChildren, GetParent, and FindLogicalNode methods for logical tree traversal. In most cases, you should not have to traverse the logical tree of existing controls, because these controls almost always expose their logical child elements as a dedicated collection property that supports collection access such as , an indexer, and so on. Tree traversal is mainly a scenario that is used by control authors who choose not to derive from intended control patterns such as ItemsControl or Panel where collection properties are already defined, and who intend to provide their own collection property support.

The visual tree also supports a helper class for visual tree traversal, VisualTreeHelper. The visual tree is not exposed as conveniently through control-specific properties, so the VisualTreeHelper class is the recommended way to traverse the visual tree if that is necessary for your programming scenario. For more information, see WPF Graphics Rendering Overview.


Sometimes it is necessary to examine the visual tree of an applied template. You should be careful when using this technique. Even if you are traversing a visual tree for a control where you define the template, consumers of your control can always change the template by setting the Template property on instances, and even the end user can influence the applied template by changing the system theme.

Routes for Routed Events as a "Tree"

As mentioned before, the route of any given routed event travels along a single and predetermined path of a tree that is a hybrid of the visual and logical tree representations. The event route can travel either in the up or down directions within the tree depending on whether it is a tunneling or bubbling routed event. The event route concept does not have a directly supporting helper class that could be used to "walk" the event route independently of raising an event that actually routes. There is a class that represents the route, EventRoute, but the methods of that class are generally for internal use only.

Resource Dictionaries and Trees

Resource dictionary lookup for all defined in a page traverses basically the logical tree. Objects that are not in the logical tree can reference keyed resources, but the resource lookup sequence begins at the point where that object is connected to the logical tree. In WPF, only logical tree nodes can have a property that contains a ResourceDictionary, therefore there is no benefit in traversing the visual tree looking for keyed resources from a ResourceDictionary.

However, resource lookup can also extend beyond the immediate logical tree. For application markup, the resource lookup can then continue onward to application-level resource dictionaries and then to theme support and system values that are referenced as static properties or keys. Themes themselves can also reference system values outside of the theme logical tree if the resource references are dynamic. For more information on resource dictionaries and the lookup logic, see XAML Resources.

See also

Sours: https://docs.microsoft.com/en-us/dotnet/desktop/wpf/advanced/trees-in-wpf

Tree wpf

What is Treeview in WPF?

What is Treeview in WPF?

Azure vs AWS

The WPF tree view supports data binding, as all other WPF controls do, but, as the tree view hierarchy does, a normal DataTemplate is often not enough. Instead, we use the Hierarchical Data template, which allows us to template both tree nodes while controlling which property to use as a source for the node's child objects. The tree view tag represents the WPF TreeView control in XAML.

Table of Content


The tree view tag represents the WPF TreeView control in XAML.


A tree view represents data in a hierarchical view of the parent-child relationship where the parent node may expand or collapse. The left sidebar of Windows Explorer is an example of a tree view.

Creating a TreeView

TreeView control contains a hierarchy of TreeViewItem controls. A TreeViewItem control is a HeaderedItemsControl that contains a collection of headers and items.

If you are defining a tree view using the Extensible Application Markup Language (XAML), you can specify the header content of a TreeViewItem control and the items created from its collection. The previous illustration illustrates this method.

You can also specify the item source as the data source and then specify a HeaderTemplate and ItemTemplate to define the TreeViewItem content.

You can also use HierarchicalDataTemplate objects to define the layout of a TreeViewItem control. For more information and example use SelectedValue, SelectedValuePath, and SelectedItem.

A Hard-Coded WPF Tree View

To get started, let's look at a typical two-tier WPF tree view that is strictly coded with the values shown in the code snippet below.


Azure vs AWS

Screenshot_1: TreeView Output

In this example, we saw how to create a normal TreeView with the help of the XAML file and in the output, we saw that we created two headers and added TreeItem to it. We did all this in the XAML file which is a static method.

Dynamic TreeView

Now we have learned to dynamically create a TreeView.

There are many templates for creating WPF tree view control and constructing it in XAML but in actual use, we are more likely to dynamically create tree view control from data. It must be in code like C#, not XAML.


Let's start with XAML:

There is a member in the Tree View class, "Items", which is an item collection. Item Collection for TreeView is a collection of Treeitems. Review item objects also have an "Items" member which is an item collection. It often forms a hierarchical structure.

We need to add at least one TreeViewItem to the object of the TreeView class. That will be the root node(s) of the TreeView. Typically, the root has a single node but multiple root nodes are possible. We then add the TreeViewItem add objects to the corresponding items in the TreeViewItem objects. The following code will make a simple tree:

TreeViewItem HeaderPart = new TreeViewItem(); HeaderPart.Header = "Vehical"; DynamicTree.Items.Add(HeaderPart); // TreeViewItem Treeitems = new TreeViewItem(); Treeitems.Header = "Car"; HeaderPart.Items.Add(Treeitems); // TreeViewItem Treeitemsone = new TreeViewItem(); Treeitemsone.Header = "Bike"; HeaderPart.Items.Add(Treeitemsone); TreeViewItem SubTreeitems = new TreeViewItem(); SubTreeitems.Header = "Shine"; Treeitemsone.Items.Add(SubTreeitems); TreeViewItem SubTreeitemsone = new TreeViewItem(); SubTreeitemsone.Header = "Activa"; Treeitemsone.Items.Add(SubTreeitemsone); TreeViewItem SubTreeitemsTwo = new TreeViewItem(); SubTreeitemsTwo.Header = "FZ-5"; Treeitemsone.Items.Add(SubTreeitemsTwo); // TreeViewItem HeaderPartOne = new TreeViewItem(); HeaderPartOne.Header = "Air vehical"; DynamicTree.Items.Add(HeaderPartOne);

The following is a tree created by the previous code:

Azure vs AWS

Screenshot_2: Dynamic TreeView

Data binding and multiple templates

WPF supports TreeView data binding, as do all other WPF controls, but, as TreeView hierarchy does a normal Datatemplate is often not enough. Instead, we use the Hierarchical Data template, which allows us to template both tree nodes while controlling which property to use as a source for the node's child objects.

A basic data-bound TreeView

In the following example, We will show you how easy it is to get started with a hierarchical data template:

.XAML file

.CS File

public MainWindow() { InitializeComponent(); MenuItem Head = new MenuItem() { Title = "Tutorial" }; MenuItem subdItem1 = new MenuItem() { Title = "Mobile Application" }; subdItem1.Items.Add(new MenuItem() { Title = "Flutter" }); subdItem1.Items.Add(new MenuItem() { Title = "React Native" }); Head.Items.Add(subdItem1); Head.Items.Add(new MenuItem() { Title = "Web-Devlopment" }); treehirmenu.Items.Add(Head); } public class MenuItem { public MenuItem() { this.Items = new ObservableCollection

The following is a tree created by the previous code:

Azure vs AWS

Screenshot_3: DataBinding TreeView

In the XAML markup, we mentioned the hierarchical data template for the TreeView item template. We instruct him to use the Items property to find the child's items by setting the template's Itemsource property, and within that, we define the actual template, which now consists only of a text block bound to the title property.

This first example was very simple, in fact so simple that we just added tree view objects manually, instead of generating a bunch of objects and then binding them. However, as things get a little more complicated, the benefits of using data bindings immediately become more apparent.


Multiple templates for different types

In the next example, we have taken a slightly more complex case, where we want to show the tree of families and their members. The family should be represented in one way, while each of its members should be shown in another way. We achieved this by creating two different templates and specifying them as the source of the tree (or window or application - which is really up to you) and then, allowing the tree view to select the appropriate template based on the type of data underlying it.

.Xaml file

.cs File

public MainWindow() { InitializeComponent(); List


Azure vs AWS

Reference: https://www.wpf-tutorial.com

As mentioned, two templates have been revealed as part of TreeView resources, allowing TreeView to select the appropriate template based on the type of data to be displayed. A specified sample for a MyFamily type is a hierarchical sample, in which the property of the members is used to show its MyFamily members.

The template defined for the MyFamily Member type is a regular data template, as there are no child members in this type. However, if we wanted each family member to have a collection of their children and possibly their children, we could use a hierarchical template instead.

In both samples, we used an image representing a family or family members, and then we show some interesting data about it, such as the number of family members or the age of the person.

In Code-Bank, we simply create two family patterns, fill each of them with a set of members, and then add each of the family to the list, which is then used as a source of items for the tree view.


While it is entirely possible to define a complete tree view using mark-up as we did in the examples above, this is not the best approach in most situations, and when you could code it later, this would have resulted in even more Code lines. Once again, the solution is data binding. Using data binding, the tree view is highly customizable and with the ability to specify multiple templates to represent different data types, the possibilities are almost endless.

Sours: https://www.ifourtechnolab.com/blog/what-is-treeview-in-wpf
15. Learn WPF in small Steps: Visual Tree, Logical Tree
Image 1


This article describes the use of control provided by WPF. It will give you a knowledge to create simple Tree, customization, Template and Binding. It mainly focuses on how to show contents in the tree view. This article will help you to understand the basics of tree view and also gives you deep knowledge to show content on tree according to your requirement.

I had to use tree view in one of my projects where I had to show image and text as most of tree has in windows. This problem started my journey to learn features provided by WPF. At the start of my journey, I found many difficulties and sometimes I said Windows application contains more user friendly controls to work with, but with the passage of time I found WPF controls more user friendly.

This article will cover the following 6 main areas:

Create Simple Tree

Image 2

If you want to create a simple tree then WPF provides you an easy way draw tree. Just add control on your page and add items in either using XAML or from code behind.

Using XAML

You can easily create a tree using XAML.

<TreeView><TreeViewItemHeader="North America"><TreeViewItemHeader="USA"></TreeViewItem><TreeViewItemHeader="Canada"></TreeViewItem><TreeViewItemHeader="Mexico"></TreeViewItem></TreeViewItem><TreeViewItemHeader="South America"><TreeViewItemHeader="Argentina"></TreeViewItem><TreeViewItemHeader="Brazil"></TreeViewItem><TreeViewItemHeader="Uruguay"></TreeViewItem></TreeViewItem></TreeView>

Using code

If you want to populate tree from code behind, then simply place your tree on form and add tree item according to your tree hierarchy.

<TreeViewName="tvMain"></TreeView>TreeViewItem treeItem = null; treeItem = new TreeViewItem(); treeItem.Header = "North America"; treeItem.Items.Add(new TreeViewItem() { Header = "USA" }); treeItem.Items.Add(new TreeViewItem() { Header = "Canada" }); treeItem.Items.Add(new TreeViewItem() { Header = "Mexico" }); tvMain.Items.Add(treeItem);

Customize Tree

Image 3

If you want to add some other controls with the content e.g. checkbox, image, etc., then you can easily design your tree without any big effort. You just need to customize the of the . You can also create class derived from and change its according to your requirement.

Using XAML

For customizing the Tree item, simply change item’s .

<TreeView><TreeViewItem><TreeViewItem.Header><StackPanelOrientation="Horizontal"><BorderBackground="Green"Width="8"Height="12"BorderBrush="#00000000"></Border><LabelContent="North America"></Label></StackPanel></TreeViewItem.Header><TreeViewItem><TreeViewItem.Header><StackPanelOrientation="Horizontal"><ImageSource="../Images/usa.png"></Image><LabelContent="USA"></Label></StackPanel></TreeViewItem.Header></TreeViewItem></TreeViewItem></TreeView>

Using Code

If you want to create header from code behind, then WPF will not disappoint you. You can change header template very smartly.

private TreeViewItem GetTreeView(string text, string imagePath) { TreeViewItem item = new TreeViewItem(); item.IsExpanded = true; StackPanel stack = new StackPanel(); stack.Orientation = Orientation.Horizontal; Image image = new Image(); image.Source = new BitmapImage (new Uri("pack://application:,,/Images/" + imagePath)); Label lbl = new Label(); lbl.Content = text; stack.Children.Add(image); stack.Children.Add(lbl); item.Header = stack; return item; }

Using overriding TreeViewItem

You can also customize by writing a new derived class for custom item. It is also pretty easy. Just create header template and assign it to property if .

publicclass ImageTreeViewItem : TreeViewItem { #region Data Member Uri _imageUrl = null; Image _image = null; TextBlock _textBlock = null; #endregion #region Properties public Uri ImageUrl { get { return _imageUrl; } set { _imageUrl = value; _image.Source = new BitmapImage(value); } } publicstring Text { get { return _textBlock.Text; } set { _textBlock.Text = value; } } #endregion #region Constructor public ImageTreeViewItem() { CreateTreeViewItemTemplate(); } #endregion #region Private Methods privatevoid CreateTreeViewItemTemplate() { StackPanel stack = new StackPanel(); stack.Orientation = Orientation.Horizontal; _image = new Image(); _image.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; _image.VerticalAlignment = System.Windows.VerticalAlignment.Center; _image.Width = 16; _image.Height = 16; _image.Margin = new Thickness(2); stack.Children.Add(_image); _textBlock = new TextBlock(); _textBlock.Margin = new Thickness(2); _textBlock.VerticalAlignment = System.Windows.VerticalAlignment.Center; stack.Children.Add(_textBlock); Header = stack; } #endregion }

Header Template

Image 4

If the style of all the elements is the same, then it is better to create template at once. Because the problem with the last example was for the same design, we add template for each tree item.

Using XAML

For creating general item template, create resource at application level, window level or at control level resource. In this example, I have created resource at control level and set the and also set the property of the .

<TreeViewName="tvMain"><TreeView.Resources><StyleTargetType="{x:Type TreeViewItem}"><SetterProperty="HeaderTemplate"><Setter.Value><DataTemplate><StackPanelOrientation="Horizontal"><CheckBoxName="chk"Margin="2"Tag="{Binding}"></CheckBox><ImageMargin="2"Source="{Binding Converter= {StaticResource CustomImagePathConvertor}}"></Image><TextBlockText="{Binding}"></TextBlock></StackPanel></DataTemplate></Setter.Value></Setter></Style></TreeView.Resources><TreeViewItemHeader="North America"IsExpanded="True"><TreeViewItemHeader="USA"></TreeViewItem><TreeViewItemHeader="Canada"></TreeViewItem><TreeViewItemHeader="Mexico"></TreeViewItem></TreeViewItem><TreeViewItemHeader="South America"IsExpanded="True"><TreeViewItemHeader="Argentina"></TreeViewItem><TreeViewItemHeader="Brazil"></TreeViewItem><TreeViewItemHeader="Uruguay"></TreeViewItem></TreeView>

It is a very interested point here that I did not pass path for each country, but shows flag with each country. I achieved by writing custom converter .

<ImageMargin="2"Source="{Binding Converter= {StaticResource CustomImagePathConverter}}"></Image>

Implement from . You can associate a value converter with binding. In this example, I am getting image path from the country name, as you can see in code.

publicclass CustomImagePathConverter : IValueConverter { #region IValueConverter Members publicobject Convert(objectvalue, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return"../Images/" + GetImageName(value.ToString()); } publicobject ConvertBack(objectvalue, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return""; } #endregion privatestring GetImageName(string text) { string name = ""; name = text.ToLower() + ".png"; return name; } }

Using Code

You can easily create template from code behind. provides you a facility to create templates. Let's see how can we achieve this exciting feature.

private DataTemplate GetHeaderTemplate() { DataTemplate dataTemplate = new DataTemplate(); FrameworkElementFactory stackPanel = new FrameworkElementFactory(typeof(StackPanel)); stackPanel.Name = "parentStackpanel"; stackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal); FrameworkElementFactory checkBox = new FrameworkElementFactory(typeof(CheckBox)); checkBox.Name = "chk"; checkBox.SetValue(CheckBox.NameProperty, "chk"); checkBox.SetValue(CheckBox.TagProperty , new Binding()); checkBox.SetValue(CheckBox.MarginProperty, new Thickness(2)); stackPanel.AppendChild(checkBox); FrameworkElementFactory image = new FrameworkElementFactory(typeof(Image)); image.SetValue(Image.MarginProperty, new Thickness(2)); image.SetBinding(Image.SourceProperty, new Binding() { Converter = new CustomImagePathConverter() }); stackPanel.AppendChild(image); FrameworkElementFactory label = new FrameworkElementFactory(typeof(TextBlock)); label.SetBinding(TextBlock.TextProperty, new Binding()); label.SetValue(TextBlock.ToolTipProperty, new Binding()); stackPanel.AppendChild(label); dataTemplate.VisualTree = stackPanel; return dataTemplate; }

Simply assign this template to of each .

DataTemplate template = GetHeaderTemplate(); foreach (WorldArea area in WorldArea.GetAll()) { TreeViewItem item = new TreeViewItem(); item.HeaderTemplate = template; item.Header = area.Name; . . . . }

Get selected checked items

You can easily get the child items from the template. Just for the example, I am showing you how to get the selected check boxes from the tree view. WPF manage control in hierarchical structure, you can access any child using class.

private List<CheckBox> GetSelectedCheckBoxes(ItemCollection items) { List<CheckBox> list = new List<CheckBox>(); foreach (TreeViewItem item in items) { UIElement elemnt = GetChildControl(item, "chk"); if (elemnt != null) { CheckBox chk = (CheckBox)elemnt; if (chk.IsChecked.HasValue && chk.IsChecked.Value) { list.Add(chk); } } List<CheckBox> l = GetSelectedCheckBoxes(item.Items); list = list.Concat(l).ToList(); } return list; } private UIElement GetChildControl(DependencyObject parentObject, string childName) { UIElement element = null; if (parentObject != null) { int totalChild = VisualTreeHelper.GetChildrenCount(parentObject); for (int i = 0; i < totalChild; i++) { DependencyObject childObject = VisualTreeHelper.GetChild(parentObject, i); if (childObject is FrameworkElement && ((FrameworkElement)childObject).Name == childName) { element = childObject as UIElement; break; } element = GetChildControl(childObject, childName); if (element != null) break; } } return element; }

Custom Objects

Image 5

WPF provides you many ways to populate tree. You can directly add your object as a in the tree and WPF gives respect to your objects and display it as you want. You just need to tell him which field will be shown in item.

Using XAML

For populating custom object in tree, you just need to create template for your object. I used for designing template.

<TreeViewName="tvMain"><TreeView.ItemTemplate><HierarchicalDataTemplateItemsSource="{Binding Path=Countries}"><StackPanelOrientation="Horizontal"Margin="4"Background="LightSeaGreen"><CheckBoxName="chk"Margin="2"Tag="{Binding Path=Name}"></CheckBox><ImageMargin="2"Source="{Binding Path=ImageUrl}"></Image><TextBlockText="{Binding Path=Name}"Margin="2"></TextBlock><StackPanel.Effect><DropShadowEffectBlurRadius="2"Color="LightGray"Opacity=".2"></DropShadowEffect></StackPanel.Effect></StackPanel></HierarchicalDataTemplate></TreeView.ItemTemplate></TreeView>

After creating template, you just need to add custom object from your code behind file, as you can see code below. I am just putting parent object in the tree. But when you will run this code, you will also see child countries are also being shown. The reason is that because I have define template in XAML for child items using .

privatevoid FillTree() { foreach (WorldArea area in WorldArea.GetAll()) { tvMain.Items.Add(area); } }

Using Code

You can also create template for your object from code behind file, as we created in previous example. The tricky part here, how can we add custom objects in the hierarchical way? Because using XAML we can write create hierarchical template. We can also create hierarchical template using code behind, but in this example I am not doing that, I am achieving the solution from other way. This technique will give you a new way to work and you can implement it in other Items controls like , etc. But in the last example, I will create hierarchical template from code behind.

privatevoid FillTree() { tvMain.ItemTemplate = GetHeaderTemplate(); tvMain.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged); foreach (WorldArea area in _list) { tvMain.Items.Add(area); } } void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) { if (tvMain.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) { foreach (WorldArea area in _list) { TreeViewItem item = (TreeViewItem)tvMain.ItemContainerGenerator.ContainerFromItem(area); if (item == null) continue; item.IsExpanded = true; if (item.Items.Count == 0) { foreach (Country country in area.Countries) { item.Items .Add(country); } } } } }

As you can see in code after adding setting template, I have registered event. generates the containers for each custom object. When we add custom object in the starts to generate container in separate thread. So we cannot get container in the next line after adding object. So you need to register event, which fires after the status change and you can get container after that.

Data Binding

Image 6

You can also bind your tree with any source as you can bind , , etc. You just need to create a template for your items as you create in other binding controls.

Using XAML

Create your hierarchical template as you created in the previous example. You may need to add inner hierarchical template for different example. But it is working fine for my example.

<TreeViewName="tvMain"><TreeView.ItemTemplate><HierarchicalDataTemplateItemsSource="{Binding Path=Countries}"><GridBackground="LightSkyBlue"Margin="2"Width="100"Height="24"><ImageMargin="2"Width="32"Height="18"Source="{Binding Path=ImageUrl}"HorizontalAlignment="Right"VerticalAlignment="Center"></Image><TextBlockMargin="2"Text="{Binding Path=Name}"VerticalAlignment="Center"FontWeight="Bold"/></Grid></HierarchicalDataTemplate></TreeView.ItemTemplate></TreeView>

Simply bind tree using property:

privatevoid BindTree() { tvMain.ItemsSource = WorldArea.GetAll(); }

Using Code

For creating Hierarchical template from code behind simply create object of class and fill childs according to your requirement and assign this template to tree.

privatevoid BindTree() { tvMain.ItemTemplate = GetTemplate(); tvMain.ItemsSource = WorldArea.GetAll(); } private HierarchicalDataTemplate GetTemplate() { HierarchicalDataTemplate dataTemplate = new HierarchicalDataTemplate(); FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid)); grid.Name = "parentStackpanel"; grid.SetValue(Grid.WidthProperty, Convert.ToDouble(100)); grid.SetValue(Grid.HeightProperty, Convert.ToDouble(24) ); grid.SetValue(Grid.MarginProperty, new Thickness(2)); grid.SetValue(Grid.BackgroundProperty, new SolidColorBrush( Colors.LightSkyBlue)); FrameworkElementFactory image = new FrameworkElementFactory(typeof(Image)); image.SetValue(Image.MarginProperty, new Thickness(2)); image.SetValue(Image.WidthProperty, Convert.ToDouble(32)); image.SetValue(Image.HeightProperty, Convert.ToDouble(24)); image.SetValue(Image.VerticalAlignmentProperty, VerticalAlignment.Center ); image.SetValue(Image.HorizontalAlignmentProperty, HorizontalAlignment.Right); image.SetBinding(Image.SourceProperty, new Binding() { Path = new PropertyPath("ImageUrl") }); grid.AppendChild(image); FrameworkElementFactory label = new FrameworkElementFactory(typeof(TextBlock)); label.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("Name") }); label.SetValue(TextBlock.MarginProperty, new Thickness(2)); label.SetValue(TextBlock.FontWeightProperty, FontWeights.Bold); label.SetValue(TextBlock.ToolTipProperty, new Binding()); grid.AppendChild(label); dataTemplate.ItemsSource = new Binding("Countries"); dataTemplate.VisualTree = grid; return dataTemplate; }

Template By Data Type

Image 7

A very nice flexibility provided by WPF is you can create your template by data type. Suppose you want have to show different type of objects in tree and you want to differentiate them on UI. It is not a big problem in WPF. Simply create Template by Data type and bind source with tree or manually add objects. Your tree will pick template according to data type.

Using Data Template

Simply create data template in any resource as I created in tree resource. And set its data type as I did using .

<TreeViewName="tvMain"><TreeView.Resources><DataTemplateDataType="{x:Type loc:WorldArea}"><BorderWidth="150"BorderBrush="RoyalBlue"Background="RoyalBlue"BorderThickness="1"CornerRadius="2"Margin="2"Padding="2"><StackPanelOrientation="Horizontal"><TextBlockText="{Binding Path=Name}"FontWeight="Bold"Foreground="White"></TextBlock></StackPanel></Border></DataTemplate><DataTemplateDataType="{x:Type loc:Country}"><BorderWidth="132"Background="LightBlue"CornerRadius="2"Margin="1"><StackPanelOrientation="Horizontal"><ImageMargin="2"Source="{Binding Path=ImageUrl}"></Image><TextBlockMargin="2"Text="{Binding Path=Name}"></TextBlock></StackPanel></Border></DataTemplate></TreeView.Resources></TreeView>

Using Hierarchical Template

You can also create hierarchical template by data type.

<TreeViewName="tvMain"><TreeView.Resources><HierarchicalDataTemplateDataType="{x:Type loc:WorldArea}"ItemsSource="{Binding Path=Countries}"><BorderWidth="150"BorderBrush="RoyalBlue"Background="RoyalBlue"BorderThickness="1"CornerRadius="2"Margin="2"Padding="2"><StackPanelOrientation="Horizontal"><TextBlockText="{Binding Path=Name}"FontWeight="Bold"Foreground="White"></TextBlock></StackPanel></Border></HierarchicalDataTemplate><HierarchicalDataTemplateDataType="{x:Type loc:Country}"><BorderWidth="132"Background="LightBlue"CornerRadius="2"Margin="1"><Grid><Grid.ColumnDefinitions><ColumnDefinitionWidth="*"></ColumnDefinition><ColumnDefinitionWidth="26"></ColumnDefinition></Grid.ColumnDefinitions><TextBlockMargin="2"Text="{Binding Path=Name}"></TextBlock><ImageGrid.Column="1"Margin="2"Source="{Binding Path=ImageUrl}"></Image></Grid></Border></HierarchicalDataTemplate></TreeView.Resources></TreeView>
Sours: https://www.codeproject.com/Articles/124644/Basic-Understanding-of-Tree-View-in-WPF

You will also like:

TreeView, data binding and multiple templates

The TreeView control:

The WPF TreeView supports data binding, like pretty much all other WPF controls does, but because the TreeView is hierarchical in nature, a normal DataTemplate often won't suffice. Instead, we use the HierarchicalDataTemplate, which allows us to template both the tree node itself, while controlling which property to use as a source for child items of the node.

A basic data bound TreeView

In the following example, I'll show you just how easy it is to get started with the HierarchicalDataTemplate:

In the XAML markup, I have specified a HierarchicalDataTemplate for the ItemTemplate of the TreeView. I instruct it to use the Items property for finding child items, by setting the ItemsSource property of the template, and inside of it I define the actual template, which for now just consists of a TextBlock bound to the Title property.

This first example was very simple, in fact so simple that we might as well have just added the TreeView items manually, instead of generating a set of objects and then binding to them. However, as soon as things get a bit more complicated, the advantages of using data bindings gets more obvious.

Multiple templates for different types

In the next example, I've taken a slightly more complex case, where I want to show a tree of families and their members. A family should be represented in one way, while each of its members should be shown in another way. I achieve this by creating two different templates and specifying them as resources of the tree (or the Window or the Application - that's really up to you), and then allowing the TreeView to pick the correct template based on the underlying type of data.

Here's the code - the explanation of it will follow right after:

As mentioned, the two templates are declared as a part of the TreeView resources, allowing the TreeView to select the appropriate template based on the data type that it's about to show. The template defined for the Family type is a hierarchical template, using the Members property to show its family members.

The template defined for the FamilyMember type is a regular DataTemplate, since this type doesn't have any child members. However, if we had wanted each FamilyMember to keep a collection of their children and perhaps their children's children, then we would have used a hierarchical template instead.

In both templates, we use an image representing either a family or a family member, and then we show some interesting data about it as well, like the amount of family members or the person's age.

In the code-behind, we simply create two Family instances, fill each of them with a set of members, and then add each of the families to a list, which is then used as the items source for the TreeView.


Using data binding, the TreeView is very customizable and with the ability to specify multiple templates for rendering different data types, the possibilities are almost endless.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click hereto help us translate this article into your language!


Sours: https://wpf-tutorial.com/treeview-control/treeview-data-binding-multiple-templates/

515 516 517 518 519