Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding TreeView selection to ViewModel

Tags:

binding

wpf

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 defined as follows:

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

My ModelView is pretty basic and contains exactly what you would expect. What I'm looking for is a way to bind a property in my ViewModel to SelectedValue. Right now, the text block displays what I need. Is there any easy way to bind this property?

like image 722
LandonSchropp Avatar asked Jun 07 '10 20:06

LandonSchropp


1 Answers

So it turns out that this is the result of not following the MVVM pattern quite correctly. The solution was to just use one ViewModel object. Inside of the ViewModel (whose type is ElementViewModel) object, I had something like:

public ElementViewModel Element {
    get {
        return this;
    }
}

Then my TreeView declaration 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.

like image 155
LandonSchropp Avatar answered Sep 24 '22 18:09

LandonSchropp