7

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?

LandonSchropp
  • 10,084
  • 22
  • 86
  • 149
  • Not entirely sure what you're asking.. Do you want the TreeView to update the VM's SelectedValue property, or the VM's SelectedValue property to update the TreeView? – hemp Jun 07 '10 at 20:19
  • Sorry if my question wasn't quite comprehensible. I'm still new to WPF. I want the TreeView to update the VM's SelectedValue property. I'm also trying to do it by using binding instead of the SelectedItemChanged event to maintain the MVVM pattern correctly. – LandonSchropp Jun 07 '10 at 20:30

3 Answers3

4

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.

LandonSchropp
  • 10,084
  • 22
  • 86
  • 149
0

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

hemp
  • 5,602
  • 29
  • 43
  • The problem seems to be that SelectedValue is read-only, so it won't let me directly bind to it. – LandonSchropp Jun 07 '10 at 20:27
  • The OneWayToSource binding mode allows you to work around read only and non-dependency properties; that's why I suggested it. This technique can work, even with a bad MVVM implementation. – hemp Dec 09 '11 at 20:00
-2

You can bind the TreeView to a property on your ViewModel directly:

This will bind to the "SelectedItem" property in the VM.

<TreeView   Name="elementTreeView"
                    ItemsSource="{Binding Elements}" 
                    SelectedValue="{Binding SelectedItem, Mode=OneWayToSource}"
                    Width="Auto"
                    SelectedValuePath="Path" />
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373