Choosing a TreeView Binding to a ViewModel

So, I have a TreeView that looks something like this:

<TreeView Name="elementTreeView" ItemsSource="{Binding Elements}" Width="Auto" SelectedValuePath="Path" /> 

I also have a TextBlock, which is defined as follows:

 <TextBlock Text="{Binding ElementName=elementTreeView, Path=SelectedValue}" /> 

My ModelView is pretty simple and contains exactly what you expect. I am looking for a way to bind a property in my ViewModel to SelectedValue. Right now the text block is displaying what I need. Is there an easy way to associate this property?

+7
wpf binding
source share
3 answers

So it turns out that this is the result of incorrectly following the MVVM pattern. The solution was to simply use a single ViewModel. Inside the ViewModel object (whose type is ElementViewModel) I had something like:

 public ElementViewModel Element { get { return this; } } 

Then my TreeView ad looked something like this:

 <TreeView Name="treeView" ItemsSource="{Binding Elements}" Width="Auto" SelectedValuePath="Element" /> 

After that, all I had to do was bind to Element in my other view.

+4
source share

You can use the BindingMode OneWayToSource to bind the TreeView SelectedValue to your ViewModel. Then bind the TextBlock Text property using OneWay binding to the same ViewModel property.

0
source share

You can directly bind TreeView to the ViewModel property:

This will be bound to the "SelectedItem" property in the virtual machine.

 <TreeView Name="elementTreeView" ItemsSource="{Binding Elements}" SelectedValue="{Binding SelectedItem, Mode=OneWayToSource}" Width="Auto" SelectedValuePath="Path" /> 
-one
source share

All Articles