How to Expand and Collapse Items in an MVVM Manner
Environment
Product Version | 2022.1.117 |
Product | RadTreeListView for WPF |
Description
How to expand and collapse items via the RadTreeListView control's public methods in an MVVM-friendly manner.
Solution
Using the IsExpandedBinding mechanism of the RadTreeListView can bring some limitations related with the UI virtualization to the forefront. When an item is outside the viewport, setting the IsExpanded properties is only reflected when a container for the item is created in some scenarios.
The public methods exposed by the control can be used in such scenarios to update the UI properly.
Here is how you can use the methods in an MVVM-friendly manner by creating appropriate Action properties:
Define the required Actions
public class WarehouseViewModel : ViewModelBase
{
public Action ExpandAllAction { get; set; }
public Action CollapseAllAction { get; set; }
public Action<object> ExpandItemAction { get; set; }
public Action<object> CollapseItemAction { get; set; }
public WarehouseViewModel()
{
}
// ...
}
Use the API of the TreeListView in the Actions
public MainWindow()
{
InitializeComponent();
var viewModel = new WarehouseViewModel();
viewModel.ExpandAllAction = () => { this.TreeListView.ExpandAllHierarchyItems(); };
viewModel.CollapseAllAction = () => { this.TreeListView.CollapseAllHierarchyItems(); };
viewModel.ExpandItemAction = (item) => { this.TreeListView.ExpandHierarchyItem(item); };
viewModel.CollapseItemAction = (item) => { this.TreeListView.CollapseHierarchyItem(item); };
this.DataContext = viewModel;
}
Invoke the ExpandItemAction and ExpandAllAction
public WarehouseViewModel()
{
this.ExpandItemCommand = new DelegateCommand(OnExpandItemCommandExecuted);
this.ExpandAllItemsCommand = new DelegateCommand(OnExpandAllItemsCommandExecuted);
}
public void OnExpandItemCommandExecuted(object item)
{
(item as WarehouseItem).IsExpanded = true;
this.ExpandItemAction(item);
}
public void OnExpandAllItemsCommandExecuted(object obj)
{
foreach (var item in this.WarehouseItems)
{
item.IsExpanded = true;
}
this.ExpandAllAction();
}