How to control selection from ViewModel of MultiSelectTreeView

277 Views Asked by At

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

1

There are 1 best solutions below

1
On BEST ANSWER

Typically, when data binding a hierarchical collection to a TreeView in WPF, the custom data items should have an IsSelected property defined in their class. If they do, then it can be data bound to the IsSelected property of each TreeViewItem:

<TreeView ItemsSource="{Binding YourCollection}" ... >
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsSelected" Value="{Binding IsSelected}" />
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

When this is done, you can just set that property to true to select an item and to false to deselect an item.

// Select Item
dataObject.IsSelected = true;

// Deselect Item
dataObject.IsSelected = false;

You can add a handler to the PropertyChanged event of each item to detect when the IsSelected property changes (if they implement the INotifyPropertyChanged interface as expected).