The Xaml TreeView control shows a list of hierarchical data, similar to a ListView.
When TreeView was first released, you populated it using the RootNode property, giving it a tree of nodes, each node referencing a data item. There was negative feedback about this nodes approach, though, from developers preferring a more data binding friendly pattern along the lines of ListView.ItemsSource.
So a TreeView.ItemsSource property was added, and now you can use either the nodes approach or the ItemsSource approach. But unlike ListView, TreeView doesn't have the corresponding SelectedItem and SelectedItems properties for single- and multi-select. Those are being added in this spec.
Also being added in this spec, for the case where the RootNode is being used instead of ItemsSource, is an API to select a single node. That is, there is a SelectedNodes property today, and this spec is adding a singular SelectedNode property.
Related GitHub issues:
microsoft/microsoft-ui-xaml#197
microsoft/microsoft-ui-xaml#124
microsoft/microsoft-ui-xaml#386
Extend TreeView selection API sets to make selections easier.
- Add
SelectedNode
: get/set the selected TreeViewNode for single selection - Add
SelectedItem
: get/set the selected item for single selection - Add
SelectedItems
: get the SelectedItems collection. - Fix existing
SelectedNodes
property: Currently this only works in multi-select mode (SelectionMode set toMultiple
). It will now also work in single selection mode (consistent with ListView).
Ouput the depth of the selected tree view node.
TreeViewNode selectedNode = treeView.SelectedNode;
if (selectedNode != null)
{
Debug.WriteLine($"Selected node depth: {selectedNode.Depth}");
}
Bind the TreeView control to a View Model with the data source and the currently selected item.
<TreeView ItemsSource="{x:Bind Descendants}"
SelectedItem="{x:Bind CurrentDescendant, Mode=TwoWay}" />
void AddToSelection(TreeView treeView, object item)
{
IList<Object> selectedItems = treeView.SelectedItems;
selectedItems.Add(item);
}
namespace Microsoft.UI.Xaml.Controls
{
[webhosthidden]
unsealed runtimeclass TreeView : Windows.UI.Xaml.Controls.Control
{
...
TreeViewNode SelectedNode{ get; set; };
Object SelectedItem{ get; set; };
Windows.Foundation.Collections.IVector<Object> SelectedItems{ get; };
...
}
}
SelectedItem(s) returns Object(collection of objects), it will be the ItemsSource type object when using databinding, or TreeViewNode when not using databinding.
Prior to WinUI 2.2, the TreeView.SelectedNodes property can only be used when the SelectionMode is set to Multiple
.
Member Name | Description |
---|---|
SelectedNode | Gets or sets the selected TreeViewNode. |
SelectedNodes | The collection of nodes that are selected in the tree. The default is an empty collection. |
SelectedItem | Gets or sets the selected item. |
SelectedItems | The collection of items that are selected in the tree. The default is an empty collection. |