Reputation: 35
In the TreeView
that I work with, I need to determine the parent node of the currently selected node. It is bound to an ObservableCollection<SomeModel>
in the viewmodel. When I inspect the currently selected node, both SelectedValue
and SelectedItem
point to the same instance of SomeModel
. How can I find the parent node then?
Everything I read on TreeView.SelectedItem
suggests to use VisualTreeHelper.GetParent()
but it takes a DependencyObject
, not a user's model, which is totally reasonable.
The binding is as follows:
<TreeView x:Name="treeViewAvailable" ItemsSource="{Binding AvailableSchemas}">
The collection in the viewmodel is as follows:
ObservableCollection<Models.Schema>? _availableSchemas;
public ObservableCollection<Models.Schema>? AvailableSchemas
{
get => _availableSchemas;
set
{
_availableSchemas = value;
NotifyPropertyChanged(MethodBase.GetCurrentMethod().Name);
}
}
The Schema
model class contains Tables
that we see in the screenshot:
public ObservableCollection<Table> Tables { get; set; } = new();
Having in the past worked with frameworks in which SelectedItem
was always the GUI component's ViewItem
and SelectedValue
was the actual model, I do not understand whether something is wrong with the XAML binding and/or viewmodel/model or whether it is by design of WPF that SelectedItem
and SelectedValue
both are the instance of the model, which feels wrong.
I see answers on SO that instruct to rig models that themselves track parent-child relationships, and that is the definition of having to write boilerplate code. It cannot be that WPF has nothing for working with TreeView
nodes.
This contradicts documentation that clearly states that SelectedItems
has to be of type TreeViewItem
:
To change the value of a selected item in a TreeView, use the SelectedItem property to access the TreeViewItem.
Upvotes: 0
Views: 36