I've got a WPF MultiSelectTreeView (downloaded from here: http://unclassified.software/en/source/multiselecttreeview).
Now I want to control, which items the user selects. A simple example is that he shouldn't be able to select child nodes of different parents. But there are also more ViewModel-specific use cases.
It's easy to achieve this in code-behind of the Window by using the PreviewSelectionChanged event, checking the conditions directly and setting the Cancel-flag accordingly. But since I want to obtain the separation of View and ViewModel, I am looking for a way of doing this in my WindowViewModel.
Of course you could also extract the check to the ViewModel and call it from the view, but it looks wrong:
WindowViewModel _viewModel;
void PreviewSelectionChanged(object sender, PreviewSelectionChangedEventArgs e)
{
e.Cancel = !this._viewModel.CanSelect(e.Item as TreeItemViewModel);
}
I hope that anybody has an idea.
- timnot90
Typically, when data binding a hierarchical collection to a
TreeView
in WPF, the custom data items should have anIsSelected
property defined in their class. If they do, then it can be data bound to theIsSelected
property of eachTreeViewItem
:When this is done, you can just set that property to
true
to select an item and tofalse
to deselect an item.You can add a handler to the
PropertyChanged
event of each item to detect when theIsSelected
property changes (if they implement theINotifyPropertyChanged
interface as expected).