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
TreeViewin WPF, the custom data items should have anIsSelectedproperty defined in their class. If they do, then it can be data bound to theIsSelectedproperty of eachTreeViewItem:When this is done, you can just set that property to
trueto select an item and tofalseto deselect an item.You can add a handler to the
PropertyChangedevent of each item to detect when theIsSelectedproperty changes (if they implement theINotifyPropertyChangedinterface as expected).